一、安装Nginx
1) 修改conf/nginx.conf
upstream tomcats {
server 127.0.0.1:18080 weight=2 max_fails=3 fail_timeout=15;
server 127.0.0.1:28080 weight=1;
server 127.0.0.1:38080 weight=1;
}
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
proxy_pass http://tomcats;
}
二、下载tomcat解压复制几份(看项目需求)
1)修改tomcat(所有的tomcat)文件夹中conf/context.xml文件,在context节点下添加如下配置:注意红色的官方给的有误,很多博客也跟着传,我也掉坑里了。复制我的就好。如下:
<Valve className="com.radiadesign.catalina.session.RedisSessionHandlerValve" />
<Manager className="com.radiadesign.catalina.session.RedisSessionManager"
host="localhost"
port="6379"
database="0"
maxInactiveInterval="60" />
2)conf/server.xml文件中的端口根据规划依次修改。要改三个地方:我的是在端口前都加了1,2,3等等
<Server port="18005" shutdown="SHUTDOWN">
<Connector port="18080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443"/>
<Connector port="18009" protocol="AJP/1.3" redirectPort="8443" />
3)在tomcat的lib文件夹下分别添加6个jar文件,这个地方jar文件的版本有可能会有冲突,配置的时候需要多尝试.
下载走这里 提取码:zeqf
三、安装并启动redis
四、在三个tomcat的webapps/ROOT目录下,修改index.jsp
<%@ page language="java" %>
<html>
<head><title>TomcatA</title></head>
<body>
<table align="centre" border="1">
<tr>
<td>Session ID</td>
<td><%= session.getId() %></td>
</tr>
<tr>
<td>Created on</td>
<td><%= session.getCreationTime() %></td>
</tr>
</table>
</body>
</html>
sessionID:<%=session.getId()%>
<br>
SessionIP:<%=request.getServerName()%>
<br>
SessionPort:<%=request.getServerPort()%>
<%
//为了区分,第二个可以是222
out.println("This is Tomcat Server 333333333333");
%>
五、验证
总结:分布式的session管理的原理是将原本放在tomcat的CurrentHashMap中的session,存放到redis中,这样多台tomcat就能实现session一致,出现这种情况的原因是由于Nginx的负载均衡导致的。其实还有另外一种最简单的session处理方式,那就是用Nginx对请求进行hash一致,这样同一会话访问的都由同一个tomcat来处理,自然不存在session不一致的情况。