nginx完成session共享

  • 2019 年 10 月 8 日
  • 筆記

首先安装niginx,跟redis

然后准备两个tomcat,修改他们的端口号

修改nginx.conf加上:

[html]

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;

}

修改nginx.conf的location成

location / {

root html;

index index.html index.htm;

proxy_pass http://backend;

}

下载tomcat-redis-session-manager相应的jar包,主要有三个:

tomcat-redis-session-manager-1.2-tomcat-7-java-7.jar,jedis-2.5.2.jar,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" %>

  1. <html>
  2. <head><title>TomcatA</title></head>
  3. <body>
  4. <table align="centre" border="1">
  5. <tr>
  6. <td>Session ID</td>
  7. <td><%= session.getId() %></td>
  8. </tr>
  9. <tr>
  10. <td>Created on</td>
  11. <td><%= session.getCreationTime() %></td>
  12. </tr>
  13. </table>
  14. </body>
  15. </html>
  16. sessionID:<%=session.getId()%>
  17. <br>
  18. SessionIP:<%=request.getServerName()%>
  19. <br>
  20. SessionPort:<%=request.getServerPort()%>
  21. <%
  22. //为了区分,第二个可以是222
  23. out.println("This is Tomcat Server 1111");
  24. %>

开启niginx服务

通过访问http://端口号/test/

刷新

可以看到虽然Server从1111变为2222,但session的创建时间没有变化,这就完成了session共享。