注意:在实际应用中,发现该方案会不定期导致Tomcat假死(怀疑Redis连接未释放),慎用。

生产环境解决方案:spring boot分布式部署集成Spring session+redis cluster实现共享Session

服务器192.168.14.132和192.168.14.133,

均已经安装tomcat,tomcat安装过程不再赘述。

采用192.168.14.132作为Redis服务器。

1.从官网下载redis

2.将redis-6.2.4.tar.gz上传至192.168.14.132的/usr/local/路径下

cd /usr/local/
tar -zvxf redis-6.2.4.tar.gz
cd redis-6.2.4/
make
make PREFIX=/usr/local/redis-6.2.4 install

3.启动redis

./bin/redis-server& ./redis.conf

4.配置

vi /usr/local/redis-6.2.4/redis.conf

更改内容:

daemonize no 改成: daemonize yes

注释掉bind 127.0.0.1 

protected-mode yes 改成: protected-mode no

取消# requirepass foobared 的注释,并改成requirepass 密码

5.设置redis开机启动

/usr/local/redis-6.2.4/bin/redis-cli shutdown  #先停止之前启动的redis

vi /etc/systemd/system/redis.service
[Unit]
Description=redis-server
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/redis-6.2.4/bin/redis-server /usr/local/redis-6.2.4/redis.conf
PrivateTmp=true

[Install]
WantedBy=multi-user.target
systemctl enable redis.service #设置为开机启动


systemctl stop redis.service     #停止redis

systemctl start redis.service    #启动redis

systemctl status redis.service   #查看redis运行状态

6.github上有人实现了tomcat基于redis的session共享,相关链接:

tomcat8.0:https://github.com/cc-chen/tomcat8.0-redis-session-manager

tomcat8.5:https://github.com/lichee/tomcat8.5-redis-session-manager

感谢大神的分享

以下步骤需分别在192.168.14.132和192.168.14.133执行。

7.将commons-pool2-2.2.jar、jedis-2.5.2.jar、tomcat8.x-redis-session-manager.jar(根据tomcat版本对应)上传至服务器tomcat安装路径下的lib文件夹下

8.修改配置文件

vi /usr/local/apache-tomcat-8.5.56/conf/context.xml
在Context节点增加:

<Valve className="com.s.tomcat.redissessions.RedisSessionHandlerValve"/> 
<Manager className="com.s.tomcat.redissessions.RedisSessionManager" 
    host="Redis服务器IP"
    port="6379"
    database="0"
    password="Redis密码"
    maxInactiveInterval="60"
    />

 

注意,这里的className,请看github页面的说明,不同版本,或有不同

9.重启tomcat即可

10.测试可更改tomcat下的Index.jsp,开启session,然后输出sessionID,查看2个服务器session是否一致

<%@ page session="true" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>

SessionID is <%=session.getId()%>

本文参考链接,感谢原文作者:

redis+tomcat实现session共享_feinifi的博客-CSDN博客_redis session共享

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐