当用户登录后,如何让缓存按用户维度区分?
解读
在国内银行、运营商、政务云等 Struts 项目里,“按用户维度缓存” 并不是简单地把数据扔进 Redis 就完事,而是要同时满足:
- 同一浏览器里切换账号,缓存不串户;
- 集群节点水平扩展时,缓存命中不漂移;
- 满足等保 2.0/3.0 对“数据隔离”的审计要求;
- 与 Struts2 自带的 org.apache.struts2.dispatcher.SessionMap 生命周期对齐,避免内存泄漏。
因此,面试官真正想听的是:你能否把“用户身份”这一维度贯穿到缓存 Key、缓存区域、失效策略、线程安全四个层面,并给出可落地的编码与运维细节。
知识点
- 用户身份锚点
国内项目普遍把 userId(Long)+ tenantCode(String) 作为联合主键,放在 Session 或 JWT Payload 里,避免登录名重复。 - Struts2 作用域
- ActionContext#getSession() 返回的是 SessionMap,本质仍绑定 HttpSession;
- ServletActionContext.getRequest().getUserPrincipal() 可拿到 Spring Security/Shiro 填充的 Principal。
- 缓存命名模式
推荐 “业务前缀:用户维度:业务键”,例如 cache:order:123456:TENANT_A。 - 两级缓存架构
本地 Caffeine 做一级,Redis 做二级;本地缓存 Key 里拼 InetAddress.getLocalHost().getHostAddress(),防止集群串读。 - 线程安全与失效
使用 Redisson 的 RLocalCachedMap,自带 write-through、expire-per-entry;或者 Spring Cache + @Cacheable(key="#root.target.genUserKey(#orderId)")。 - 登出/踢出时主动清缓存
监听 Struts2 的 SessionListener 或 Spring Security 的 InteractiveSessionExpiredEvent,调用 redisTemplate.delete(cache:order:*:TENANT_A)。
答案
步骤一:在登录成功后,把 userId 与 tenantCode 写入 Session
ActionContext ctx = ActionContext.getContext();
Map<String, Object> session = ctx.getSession();
session.put("uid", user.getId());
session.put("tenant", user.getTenantCode());
步骤二:封装用户维度缓存工具类
public final class UserCacheKit {
private static final String SEP = ":";
private static final String PREFIX = "cache:order";
public static String buildKey(String businessKey) {
Map<String, Object> session = ActionContext.getContext().getSession();
Long uid = (Long) session.get("uid");
String tenant = (String) session.get("tenant");
return PREFIX + SEP + businessKey + SEP + uid + SEP + tenant;
}
}
步骤三:在 Service 层按需缓存
@Cacheable(value="orderCache", key="T(com.xxx.UserCacheKit).buildKey(#orderId)")
public OrderVO findOrder(Long orderId) { ... }
步骤四:登出时主动失效
public String logout() {
Map<String, Object> session = ActionContext.getContext().getSession();
String pattern = "cache:order:*:" + session.get("uid") + ":" + session.get("tenant");
RedisUtils.delByPattern(pattern); // 使用 redisTemplate.keys + delete
session.clear();
return "login";
}
通过以上四步,缓存 Key 天然带用户维度,集群环境下 Redis 按 Key 做哈希分片,既满足性能,又通过等保审计。
拓展思考
- 多终端登录
如果允许同一账号在 PC 和 APP 同时在线,可在 Key 里再拼 clientType,变成 cache:order:123456:UID:TENANT:PC。 - 灰度发布
利用 “用户维度”做灰度缓存:在网关层把灰度用户路由到带 “gray” 标签的缓存分区,实现 零停机切换。 - 敏感数据加密
等保要求“个人信息加密存储”,可在 Redisson 配置开启 FST + AES 字段级加密,密钥按租户隔离,加密后 Key 长度不变,对现有命名模式无侵入。