用 Nginx 反向代理多台服务器的时候,会出现 session 不同步的问题,如用户在tomcat1中登录,保存了用户信息进 session 中,但是tomcat2中的 session 中没有该用户信息,如果用户再次发出请求时分配到了 tomcat2 中,就会出现 找不到用户 session信息,重新调整到登录页面的情况,所以,采用session广播的方式,可以使不同的 tomcat 之间 session 共享,来解决这个问题。
步骤:
tomcat部分:
先部署好两台(或者多台)tomcat,具体步骤参考我的另一篇博客:https://blog.csdn.net/DGH2430284817/article/details/90417905
到每一个tomcat中的conf目录下打开 server.xml ,在
<Engine defaultHost="localhost" name="Catalina" jvmRoute="tomcat">
下添加配置(固定的,localhost如果是远程的可以修改对应ip):
<Engine defaultHost="localhost" name="Catalina" jvmRoute="tomcat">
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster" channelSendOptions="8">
<Manager className="org.apache.catalina.ha.session.DeltaManager" expireSessionsOnShutdown="false"
notifyListenersOnReplication="true"/>
<Channel className="org.apache.catalina.tribes.group.GroupChannel">
<Membership className="org.apache.catalina.tribes.membership.McastService"
address="228.0.0.4" port="45564" frequency="500" dropTime="3000"/>
<Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
address="localhost" port="14000" autoBind="100" selectorTimeout="5000" maxThreads="6"/>
<Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
<Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
</Sender>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/>
</Channel>
<Valve className="org.apache.catalina.ha.tcp.ReplicationValve" filter=""/>
<Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>
<ClusterListener className="org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener"/>
<ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
</Cluster>
web项目部分:
然后就是tomcat中的web项目了,在web.xml中添加配置 <distributable/>
最后web项目中可以添加一个jsp页面,用来查看不同的tomcat的session 是否相同(index2.jsp):
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body class="signin">
tomcat01 <br>
session:<%=session.getId()%>
</body>
</html>
里面的tomcat01是用来确定是哪个tomcat中的web项目,另一个改为tomcat02
nginx部分:
修改conf目录下的 nginx.conf 文件:
upstream tomcatServer{
server 127.0.0.1:8080;
server 127.0.0.1:8082;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://tomcatServer/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
配置完成,启动 nginx 和 tomcat 跑起项目,然后不断刷新 index2.jsp 页面,看session信息是否相同。
我的访问地址是http://127.0.0.1/medical-web-boss/index2.jsp,根据不同的项目名,
你们可自行修改http://127.0.0.1/项目名/index2.jsp
结果:
tomcat01
tomcat02
成功!!
注意:
这种广播的模式虽然共享了session,但是缺点明显,如session 的同步是有延迟的,而且同步也是要消耗资源,降低性能的,就连官方都不建议使用这种方式来解决分布式session问题,如果tomcat数量在4个左右的时候可以考虑使用这种方式。