Nginx+Tomcat关于Session的管理的实现

2019-10-18 19:53:17丽君

安装完成以后配置文件/etc/redis.conf

启动redis服务端

redis-server /etc/redis.conf

启动客户端

redis-cli

2.Tomcat引入依赖的jar

$TOMCAT_HOME/lib添加如下jar包

<dependency>
  <groupId>com.bluejeans</groupId>
  <artifactId>tomcat-redis-session-manager</artifactId>
  <version>2.0.0</version>
</dependency>
<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>2.5.2</version>
</dependency>
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-pool2</artifactId>
  <version>2.2</version>
</dependency>

3.Tomcat修改配置

修改$TOMCAT_HOME/conf目录下的context.xml文件

<Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />
<Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"
     host="localhost"
     port="6379"
     database="0"
     maxInactiveInterval="60"/>

Tomcat提供了一个开放的session管理和持久化的org.apache.catalina.session.ManagerBase,继承这个抽象类并做一些简单的配置,即可让你的session管理类接管Tomcat的session读取和持久化,这里使用的是tomcat-redis-session-manager来管理session;

RedisSessionManager继承于org.apache.catalina.session.ManagerBase类,对session的相关操作都在此类中;

4.测试

第一次请求http://ip/

key is null,ready init..... 
sessionID:1131499E5A65DE1591152465E7B24B1F 
sessionCreateTime:1527740273682
tomcat port 8081

第二次刷新http://ip/

key is not null,key=value 
sessionID:1131499E5A65DE1591152465E7B24B1F 
sessionCreateTime:1527740273682
tomcat port 8081

将tomcat-8081停掉, 第三次刷新http://ip/

key is not null,key=value 
sessionID:1131499E5A65DE1591152465E7B24B1F 
sessionCreateTime:1527740273682
tomcat port 8082

可以发现此时消息已经转发到tomcat-8082节点了,但是session没有改变,同时key也可以获取到值;

5.查看redis

[root@localhost ~]# redis-cli
127.0.0.1:6379> keys *
1) "1131499E5A65DE1591152465E7B24B1F"
127.0.0.1:6379> get 1131499E5A65DE1591152465E7B24B1F
"xacxedx00x05srx00Dcom.orangefunction.tomcat.redissessions.SessionSerializationMetadataBxd9xd9xf7vxa2xdbLx03x00x01[x00x15sessionAttributesHashtx00x02[Bxpwx14x00x00x00x10}xc8xc9xcfxf6xc3xb5Yxc7x0cx8eFxa5xfaQxe8xsrx00x0ejava.lang.Long;x8bxe4x90xccx8f#xdfx02x00x01Jx00x05valuexrx00x10java.lang.Numberx86xacx95x1dx0bx94xe0x8bx02x00x00xpx00x00x01cxb4jx94x12sqx00~x00x03x00x00x01cxb4jx94x12srx00x11java.lang.Integerx12xe2xa0xa4xf7x81x878x02x00x01Ix00x05valuexqx00~x00x04x00x00absrx00x11java.lang.Booleanxcd rx80xd5x9cxfaxeex02x00x01Zx00x05valuexpx01qx00~x00nsqx00~x00x03x00x00x01cxb4jx94*tx00 1131499E5A65DE1591152465E7B24B1Fsqx00~x00ax00x00x00x01tx00x03keytx00x05valuewbx00x00x01cxb4jx94x12"