1、环境
CentOS6.5
JDK1.7
Tomcat6.0
Nginx1.7.4
Redis3.2.6
Ngin安装及负载均衡请查看:http://blog.csdn.net/llgyzb/article/details/56831031
Redis安装及配置请查看:http://blog.csdn.net/llgyzb/article/details/56851203
2、配置负载均衡
我有两个Tomcat
tomcat1 192.168.0.101:8081
tomcat2 192.168.0.102:8081
先配置负载均衡,请参考http://blog.csdn.net/llgyzb/article/details/56831031
启动Nginx
3、配置tomcat
下载tomcat-redis-session-manager相应的jar包,主要有三个:
tomcat-redis-session-manager-1.2-tomcat-6-Java-7.jar
(第一个包下载失败的话,也可以在这里下载:http://download.csdn.net/download/u014002509/8678471)
jedis-2.5.2.jar
commons-pool2-2.2.jar
所有Jar文件可从这里下载:http://download.csdn.net/detail/llgyzb/9765586
下载完成后拷贝到$TOMCAT_HOME/lib中
修改两tomcat的context.xml:
<Context>
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
<Valve className="com.radiadesign.catalina.session.RedisSessionHandlerValve" />
<Manager className="com.radiadesign.catalina.session.RedisSessionManager"
host="192.168.0.101"
port="6379"
database="0"
maxInactiveInterval="60"
/>
</Context>
上面的192.168.0.101是我Redis所在的服务器IP(切记,要修改redis文件目录下配置文件redis.conf中bin 127.0.0.1 为 bin 192.168.0.101,这样其他服务器上的tomcat才可以连接redis,可参考http://blog.csdn.net/llgyzb/article/details/56851203)。
RedisSessionHandlerValue和RedisSessionManager类的包名要与你拷到Lib下jar包中相应类名对应的包名一致。
在tomcat1/webapps/test放一个index.jsp
<%@ page language="java" %>
<html>
<head><title>TomcatA</title></head>
<body>
<table align="centre" border="1">
<tr>
<td>Session ID</td>
<% session.setAttribute("tomcat.session.id","tomcat.session.id.1"); %>
<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 1111"); %>
在第二个tomcat的webapps/test/index.jsp添加如下内容
<%@ page language="java" %>
<html>
<head><title>TomcatB</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()%>
<% =session.getAttribute("tomcat.session.id") %>
<br> SessionIP:<%=request.getServerName()%> <br> SessionPort:<%=request.getServerPort()%> <% //为了区分,第二个可以是222 out.println("This is Tomcat Server 222"); %>
重启tomcat和nginx,再次访问ngiunx即可看到sessionID不再改变,已经实现共享