tomcat实现分布式session

tomcat-redis-session-manager

使用

Copy the following files into the TOMCAT_BASE/lib directory:

1
2
3
tomcat-redis-session-manager-VERSION.jar
jedis-2.5.2.jar
commons-pool2-2.2.jar

配置 TOMCAT_HOME/conf/context.xml

1
2
3
4
5
<Valve className="com.radiadesign.catalina.session.RedisSessionHandlerValve" />
<Manager className="com.radiadesign.catalina.session.RedisSessionManager"
host="localhost"
port="6379" database="0"
maxInactiveInterval="30" />

mvn 里搜 Tomcat Redis Session Manager

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/com.bluejeans/tomcat-redis-session-manager -->
<dependency>
<groupId>com.bluejeans</groupId>
<artifactId>tomcat-redis-session-manager</artifactId>
<version>2.0.0</version>
</dependency>

相关类

1
2
3
4
5
6
7
8
9
10
11
12
13
RedisSessionHandlerValve

RedisSession

RedisSessionManager

JavaSerializer

DeserializedSessionContainer

Serializer

SessionSerializationMetadata

其中 RedisSessionHandlerValve 是在 context 层配置的 value.

RedisSessionManager 继承自 tomcat 的 ManagerBase,实现 Lifecycle 接口.

RedisSession 继承自 tomcat 的 StandardSession.

RedisSessionHandlerValve 对 session 的处理

1
2
3
4
5
6
7
8
9
10
11
- RedisSessionHandlerValve.invoke()
- 1.调用后续value.invoke()
- 2.RedisSessionManager.afterRequest()
- 1.从ThreadLocal中取出当前线程对应的redisSession
- 2.若有,则复用父类StandardSession.isValid()判断session是否失效
- 2.1.若未失效,则save()保存session到redis
- 若SessionPersistPolicy即session持久化策略为ALWAYS_SAVE_AFTER_REQUEST,则通过jedis获取连接,将redisSession序列化成sessionAttributesHash.
最终存入redis的key是sessionId,value是序列化后的updatedSerializationMetadata.
设置key的失效时间为session的最大失效时间 jedis.expire(binaryId, getMaxInactiveInterval())
- 2.2.若session失效,则从redis中remove()掉session
- 通过jedis.del(session.getId())删除session

相关操作

getSession() 从 redis 中 获取, createSession() 存入 redis.

load() 和 unload() 都是 空逻辑,因为生命周期交给redis管理了.

session清理 也不需要做了,向redis中存入key的时候已经设置了key的失效时间.

@see

tomcat-redis-session-manager github