本文記錄nginx+redis+tomcat實(shí)現(xiàn)session共享的過程
nginx安裝:http://www.aygfsteel.com/fanyingjie/archive/2016/04/22/430204.html
redis安裝:http://www.aygfsteel.com/fanyingjie/archive/2016/04/22/430203.html
準(zhǔn)備兩個tomcat,修改相應(yīng)的端口
名稱 | IP | 端口 | tomcat版本 | JDK |
tomcat1 | 10.10.49.23 | 8080 | 7.0.40 | 1.7.0_25 |
tomcat2 | 10.10.49.15 | 8081 | 7.0.40 | 1.7.0_25 |
修改nginx.conf加上:
- upstream backend {
- server 10.10.49.23:8080 max_fails=1 fail_timeout=10s;
- server 10.10.49.15:8081 max_fails=1 fail_timeout=10s;
- }
- location / {
- root html;
- index index.html index.htm;
- proxy_pass http://backend;
- }
啟動nginx。
下載tomcat-redis-session-manager相應(yīng)的jar包,主要有三個:
wget https://github.com/downloads/jcoleman/tomcat-redis-session-manager/tomcat-redis-session-manager-1.2-tomcat-7-Java-7.jar
wget http://central.maven.org/maven2/redis/clients/jedis/2.5.2/jedis-2.5.2.jar
wget http://central.maven.org/maven2/org/apache/commons/commons-pool2/2.0/commons-pool2-2.0.jar
下載完成后拷貝到$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.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />
- <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"
- host="10.10.49.20"
- port="6379"
- database="0"
- maxInactiveInterval="60" />
- </Context>
在tomcat/webapps/test放一個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()%>
- <%
- //為了區(qū)分,第二個可以是222
- out.println("This is Tomcat Server 1111");
- %>
啟動tomcat,發(fā)現(xiàn)有異常:com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve 類找不到
分別打開三個jar包,確實(shí)沒有這個類,解決可以參考:
http://www.aygfsteel.com/fanyingjie/archive/2016/04/22/430205.html
通過訪問http://10.10.49.20/test/
刷新:
可以看到雖然Server從1111變?yōu)?222,但session的創(chuàng)建時間沒有變化,這就完成了session共享。