如何开发自定义会话管理器?
解读
在国内互联网与金融级 Java 项目中,默认的 StandardManager 或 PersistentManager 往往无法满足“会话共享、高可用、水平扩展、安全合规”三大硬性指标。面试官抛出此题,核心想验证三点:
- 是否真正读过 org.apache.catalina.Manager/Session 源码,理解生命周期与并发模型;
- 能否把“分布式缓存、序列化、故障转移、监控报警”这些生产刚需落地到 Tomcat 内部;
- 是否具备“不破坏容器行为、不侵入业务代码”的框架设计能力。
因此,回答必须围绕“接口契约—线程安全—集群感知—监控埋点”四段式展开,并给出可直接落地的实现步骤与验证脚本。
知识点
-
核心接口与类
- org.apache.catalina.Manager:会话池入口,负责 createSession、findSession、removeSession、backgroundProcess。
- org.apache.catalina.Session:会话数据载体,关键字段 id、creationTime、lastAccessedTime、maxInactiveInterval、isValid。
- org.apache.catalina.session.StandardSession:官方默认实现,已实现 Serializable、HttpSession、AccessController 逻辑,可继承复用。
- org.apache.catalina.session.ManagerBase:抽象骨架,已解决锁竞争、SessionIdGenerator、JMX 注册、background 线程调度,强烈建议继承。
-
生命周期回调
- initInternal():读取 context.xml 中自定义属性(如 Redis 节点、连接池大小)。
- startInternal():初始化数据源、热加载序列化器、开启后台线程。
- stopInternal():释放连接池、刷盘剩余会话、注销 JMX。
- destroy():清理静态引用,防止 Web 应用重载时 ClassLoader 泄漏。
-
线程安全与并发
- ManagerBase 内部使用 ConcurrentHashMap<String, Session> 存储会话,需保证 findSession/removeSession 复合操作原子性;推荐 Session 自身采用 ReentrantReadWriteLock,读多写少场景性能优于 synchronized。
- 背景线程每分钟触发一次 backgroundProcess(),负责过期剔除与持久化,必须 catch 全部异常,防止杀死 ContainerBackgroundProcessor 线程。
-
集群一致性
- 通过 org.apache.catalina.ha.session.DeltaManager 或 BackupManager 复制会话,但金融场景更倾向外部缓存。自定义管理器只需在 createSession、removeSession、expire 时向 Redis/Memcached 发 Pub/Sub 或 SET/EX 指令即可,无需实现 ClusterListener。
- 序列化方案务必实现 org.apache.catalina.session.Store,底层可用 Kryo、Protobuf、JDK Serializable;注意 ClassLoader 隔离,使用 Thread.contextClassLoader 反序列化。
-
监控与报警
- 实现 org.apache.catalina.SessionListener,在 sessionEvent 中统计新建、过期、拒绝次数,通过 Micrometer 写入 Prometheus。
- 暴露 JMX MBean:ActiveSessions、RejectedSessions、AverageAliveTime,供阿里云 ARMS、腾讯云 TSF 集成。
-
国内合规
- 《个人信息保护法》要求会话数据出境审计,若 Redis 部署在云上,需开启 TLS 与透明加密,自定义管理器需在 initInternal() 中加载国密 SM4 密钥。
- 等保 2.0 三级要求“剩余信息保护”,重写 expire() 方法,在删除缓存前用 0 覆盖敏感字段。
答案
步骤一:继承 ManagerBase,声明最小配置属性
public class RedisSessionManager extends ManagerBase {
private String nodes = "127.0.0.1:6379";
private int database = 0;
private String password;
private int timeout = 2000;
private JedisPool pool;
private final SessionIdGenerator idGenerator = new StandardSessionIdGenerator();
}
步骤二:覆盖 initInternal,读取 context.xml 参数并初始化连接池
@Override
protected void initInternal() throws LifecycleException {
super.initInternal();
nodes = getContainer().findParameter("redis.nodes");
password = getContainer().findParameter("redis.password");
GenericObjectPoolConfig<?> cfg = new GenericObjectPoolConfig<>();
cfg.setMaxTotal(128);
cfg.setMaxIdle(64);
cfg.setTestOnBorrow(true);
pool = new JedisPool(cfg, nodes.split(",")[0].split(":")[0],
Integer.parseInt(nodes.split(",")[0].split(":")[1]),
timeout, password, database);
}
步骤三:覆盖 createSession,保证集群唯一且立即落库
@Override
public Session createSession(String sessionId) {
String id = (sessionId == null) ? idGenerator.generateSessionId() : sessionId;
RedisSession session = new RedisSession(this, id);
session.setNew(true);
session.setValid(true);
session.setCreationTime(System.currentTimeMillis());
session.setMaxInactiveInterval(getMaxInactiveInterval());
sessions.put(id, session); // 本地缓存
saveInternal(session, true); // 同步写 Redis
return session;
}
步骤四:实现 saveInternal 与 loadSession,采用 Hash+TTL 结构
private void saveInternal(RedisSession session, boolean force) {
try (Jedis jedis = pool.getResource()) {
byte[] key = ("TOMCAT_SESSION:" + session.getId()).getBytes(StandardCharsets.UTF_8);
Map<byte[], byte[]> map = new HashMap<>();
map.put("data".getBytes(), serialize(session));
jedis.hset(key, map);
jedis.expire(key, Math.max(30, session.getMaxInactiveInterval()));
}
}
private RedisSession loadSession(String id) {
try (Jedis jedis = pool.getResource()) {
byte[] key = ("TOMCAT_SESSION:" + id).getBytes();
byte[] data = jedis.hget(key, "data".getBytes());
if (data == null) return null;
RedisSession s = deserialize(data);
s.setManager(this);
return s;
}
}
步骤五:覆盖 findSession,本地未命中则回源 Redis
@Override
public Session findSession(String id) throws IOException {
Session s = sessions.get(id);
if (s != null && s.isValid()) {
s.access(); // 更新 lastAccessedTime
return s;
}
s = loadSession(id);
if (s != null) sessions.put(id, s);
return s;
}
步骤六:backgroundProcess 中批量过期
@Override
public void backgroundProcess() {
int expired = 0;
for (Iterator<Session> it = sessions.values().iterator(); it.hasNext(); ) {
Session s = it.next();
if (!s.isValid() || s.getExpireTime() < System.currentTimeMillis()) {
it.remove();
removeInternal(s, true);
expired++;
}
}
if (getLogger().isDebugEnabled()) getLogger().debug("Expired " + expired + " sessions");
}
步骤七:在 context.xml 中声明并启动
<Manager className="com.xxx.RedisSessionManager"
redis.nodes="10.0.0.101:6379,10.0.0.102:6379"
redis.password="${REDIS_PWD}"
maxInactiveInterval="1800"/>
步骤八:验证
- 启动两个 Tomcat 实例,端口 8080/8081,前端用 Nginx ip_hash 保持粘性。
- 关闭 8080,刷新页面,会话未丢失即成功。
- 通过 Arthas 命令
ognl -x 3 @com.xxx.RedisSessionManager@pool查看连接池活性,确认无泄漏。
拓展思考
-
多租户场景下,同一 Tomcat 实例承载多个 webapp,如何防止 Session 前缀冲突?
答:在 key 中加入ContextPath与jvmRoute,如TOMCAT_SESSION:{context}:{jvmRoute}:{id},并覆写 generateSessionId() 把 jvmRoute 拼接到尾部,确保全局唯一。 -
当 Redis 出现大面积延迟,如何降级到本地内存并保证数据最终一致?
答:在 saveInternal 与 loadSession 中捕获 JedisConnectionException,把 session 标记为“dirty”并写入内存队列;后台线程定时重试 Redis,成功后再清除 dirty 标记。提供开关redis.degrade=true供运维热更新。 -
国内金融云要求“双活+异地冷备”,Redis 主备切换期间如何做到零会话丢失?
答:引入 Redisson 的 RLock 与 RMap 结合 WAIT 命令,保证写入至少同步到 1 个从节点;同时开启 AOF 每秒刷盘,Tomcat 侧在 removeInternal 阶段执行 WAIT 2 1000,超时即报警但不阻塞用户请求,实现“弱一致+高可用”。 -
未来升级到 Jakarta EE 10,Servlet 6.0 提供 HttpSession#changeSessionId() 防固定攻击,自定义管理器如何适配?
答:覆写 changeSessionId(String oldId, String newId) 方法,采用 Redis 的 RENAME key 原子命令,同时更新本地 ConcurrentHashMap,确保在集群节点间即时生效。