概述
web项目中,Tomcat的访问量总是有限的,这时候就需要用到Tomcat集群,多个Tomcat的时候就要考虑Session共享的问题,这里介绍一种使用Memcached做Session共享的解决方案
环境
操作系统:Linux( centOS 6..5 版)
软件:Tomcat7
Memcached
实现原理
Tomcat + Memcached 实现session共享流程图
配置
- 安装Tomcat 2个和Memcached 1个,参考【Linux】Tomcat安装及一个服务器配置多个Tomcat 和 【Linux】Memcached安装
- 配置Tomcat,到tomcat的安装目录lib中,加入:需要的jar包
maven下依赖如下:
1 <dependency> 2 <groupId>asm</groupId> 3 <artifactId>asm</artifactId> 4 <version>3.2</version> 5 </dependency> 6 7 <dependency> 8 <groupId>com.couchbase.client</groupId> 9 <artifactId>couchbase-client</artifactId> 10 <version>1.4.11</version> 11 </dependency> 12 13 <dependency> 14 <groupId>com.googlecode</groupId> 15 <artifactId>kryo</artifactId> 16 <version>1.04</version> 17 </dependency> 18 19 <dependency> 20 <groupId>de.javakaffee</groupId> 21 <artifactId>kryo-serializers</artifactId> 22 <version>0.11</version> 23 </dependency> 24 25 <dependency> 26 <groupId>de.javakaffee.msm</groupId> 27 <artifactId>memcached-session-manager</artifactId> 28 <version>1.8.2</version> 29 </dependency> 30 31 <dependency> 32 <groupId>de.javakaffee.msm</groupId> 33 <artifactId>memcached-session-manager-tc7</artifactId> 34 <version>1.8.2</version> 35 </dependency> 36 37 <dependency> 38 <groupId>com.googlecode</groupId> 39 <artifactId>minlog</artifactId> 40 <version>1.2</version> 41 </dependency> 42 43 <dependency> 44 <groupId>de.javakaffee.msm</groupId> 45 <artifactId>msm-kryo-serializer</artifactId> 46 <version>1.8.2</version> 47 </dependency> 48 49 <dependency> 50 <groupId>com.esotericsoftware</groupId> 51 <artifactId>reflectasm</artifactId> 52 <version>1.01</version> 53 </dependency> 54 55 <dependency> 56 <groupId>net.spy</groupId> 57 <artifactId>spymemcached</artifactId> 58 <version>2.11.4</version> 59 </dependency>
- 在tomcat安装目录下的context.xml文件中加入:
1 <Manager 2 className="de.javakaffee.web.msm.MemcachedBackupSessionManager" 3 memcachedNodes="n1:127.0.0.1:11211" 4 sticky="false" 5 sessionBackupAsync="false" 6 requestUriIgnorePattern=".*\.(ico|png|gif|jpg|jpeg|bmp|css|js|html|htm)$" 7 transcoderFactoryClass="de.javakaffee.web.msm.serializer.kryo.KryoTranscoderFactory" 8 />
- 在tomcat安装目录下的server.xml文件中加入:
1 <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat1">
第二个Tomcat中设置 jvmRoute="tomcat2", 用来区分tomcat
- 在tomcat中添加测试界面,session.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <BR> 4 SessionID:<%=session.getId()%> 5 <BR> 6 SessionIP:<%=request.getServerName()%> 7 <BR> 8 SessionPort:<%=request.getServerPort()%> 9 <BR>
- 在同一个浏览器中,打开2个tomcat的测试界面,sessionId相同,表示通过Memcached实现的session共享,如下
注:此方案和可以配合nginx使用,利用nginx分发请求来访问不同的tomcat,而session又是共享的