如果单台tomcat就不存在session的问题,如果是多台就需要考虑session共享的问题,或者nginx配置ip_hash可以解决session的问题,但是ip_hash的弊端是客户只能访问一台机器,那台机挂了就报错了不实用。因此这里我们采用memcache+tomcat+nginx来实现。
案例:
安装memache
yum -y install memcached
systemctl start memcached
安装nginx和tomcat
nginx配置成负载均衡
- [root@svr5 ~]# vim /usr/local/nginx/conf/nginx.conf
- .. ..
- upstream tomcatgrp {
- server 192.168.2.100:8080;
- server 192.168.2.200:8080;
- }
- server {
- listen 80;
- server_name localhost;
- location / {
- proxy_pass http://tomcatgrp;
- root html;
- index index.html index.htm;
- }
- }
/usr/local/nginx/sbin/nginx -s reload
修改tomcat的配置
- [root@svr100 ~]# ~]# vim /usr/local/tomcat/conf/context.xml
- <Context>
- <Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
- memcachedNodes="mem1:192.168.2.5:11211"
- requestUriIgnorePattern=".*.(ico|png|gif|jpg|css|js)$"
- transcoderFactoryClass="de.javakaffee.web.msm.JavaSerializationTranscoderFactory"/>
####固定格式:transcoderFactoryClass="de.javakaffee.web.msm.serializer.javolution.JavolutionTranscoderFactory"/>
- </Context>
下载需要的jar包拷贝到/usr/local/tomcat/lib下
下载地址:https://www.mvnjar.com
- asm-5.1.jar minlog-1.3.0.jar
- kryo-3.0.3.jar msm-kryo-serializer-1.9.2.jar
- kryo-serializers-0.34.jar reflectasm-1.11.1.jar
- memcached-session-manager-1.9.2.jar spymemcached-2.11.1.jar
- memcached-session-manager-tc8-1.9.2.jar #要是tomcat7就用 tc7
分别在两台机器上添加测试页
webapp/ROOT/session.jsp
<%@ page language="java" %>
<html>
<head><title>TomcatA</title></head>
<body>
<h1><font color="red">TomcatA.test</font></h1>
<table align="centre" border="1">
<tr>
<td>Session ID</td>
<% session.setAttribute("test","test"); %>
<td><%= session.getId() %></td>
</tr>
<tr>
<td>Created on</td>
<td><%= session.getCreationTime() %></td>
</tr>
</table>
</body>
</html> - 测试http://ip/session.jsp
-
测试可以先将浏览器缓存清理后进行,也可以反向验证(停掉memcache对比测试)