Tomcat Session共享
通过memcached共享session
相关的jar包
- tomcat 6:memcached-session-manager-tc6
- tomcat 7:memcached-session-manager-tc7
<dependency> <groupId>de.javakaffee.msm</groupId> <artifactId>memcached-session-manager-tc6</artifactId> <version>1.8.2</version> </dependency>
还有如果要用kryo来替换java默认的序列化方法(推荐),还需要:
<dependency> <groupId>de.javakaffee.msm</groupId> <artifactId>memcached-session-manager-tc6</artifactId> <version>1.8.2</version> </dependency> <dependency> <groupId>de.javakaffee.msm</groupId> <artifactId>msm-kryo-serializer</artifactId> <version>1.8.2</version> </dependency> <dependency> <groupId>de.javakaffee</groupId> <artifactId>kryo-serializers</artifactId> <version>0.11</version> </dependency> <dependency> <groupId>com.googlecode</groupId> <artifactId>kryo</artifactId> <version>1.04</version> </dependency>
通过maven取出并不一定全要,可以取以下部分放到CATALINA_BASE/lib
:
memcached-session-manager-1.8.2.jar memcached-session-manager-tc6-1.8.2.jar spymemcached-2.11.1.jar commons-codec-1.5.jar couchbase-client-1.4.0.jar kryo-1.04.jar kryo-serializers-0.11.jar msm-kryo-serializer-1.8.2.jar minlog-1.2.jar reflectasm-1.01.jar asm-3.2.jar
session 配置
修改$CATALINA_BASE/conf/context.xml
,比如用kryo来序列化Session。注意如果是
多个tomcat共享session的话就一定要选择非粘着(none-sticky)Session:
<Context> ... <Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager" memcachedNodes="n1:host1.yourdomain.com:11211,n2:host2.yourdomain.com:11211" sticky="false" sessionBackupAsync="false" lockingMode="uriPattern:/path1|/path2" requestUriIgnorePattern=".*\.(ico|png|gif|jpg|css|js)$" transcoderFactoryClass="de.javakaffee.web.msm.serializer.kryo.KryoTranscoderFactory" /> </Context>
通过观察页面上显示的SessionId来看是不是同一个Session:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Test Session Page</title> </head> <body> This is A : ${pageContext.session.id} </body> </html>
参考:
- https://code.google.com/p/memcached-session-manager/wiki/SetupAndConfiguration
- http://chenzhou123520.iteye.com/blog/1650212
- http://gong1208.iteye.com/blog/1596120
通过redis共享session
redis+tomcat-sessoin-manager
相关jar包
- jedis-2.5.2.jar
- commons-pool2-2.0.jar
- tomcat-redis-session-manager1.2.jar
Tomcat配置
$CATALINA_BASE/conf/context.xml
:
<Context> <!-- ... ---> <Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" /> <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager" host="127.0.0.1" port="6379" database="0" maxInactiveInterval="60" /> <!-- ... ---> </Context>