memcached-session-manager是GitHub上的一个开源项目,可以实现基于Memcached的Session共享,官网地址:http://code.google.com/p/memcached-session-manager/
具有如下特性:
1,Supports Tomcat 6 and Tomcat 7
2,Handles sticky or non-sticky sessions
3,No Single Point of Failure
4,Handles tomcat failover
5,Handles memcached failover
6,Comes with pluggable session serialization
7,Allows asynchronous session storage for faster response times
8,Sessions are only sent to memcached if they're actually modified
9,JMX management & monitoring
配置:
1,Tomcat,tomcat/lib下新增如下jar包:
2,conf/context.xml配置:
<Context>
<Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
memcachedNodes="n1:172.16.205.186:11211"
sticky="false"
sessionBackupAsync="false"
lockingMode="auto"
requestUriIgnorePattern=".*\.(ico|png|gif|jpg|css|js)$" />
</Context>
3,Nginx配置随机分发:
upstream tomcat_server {
server 172.16.205.186:9080;
server 172.16.205.182:9080;
}
location / {
proxy_pass http://tomcat_server;
root html;
index index.html index.htm;
}
4,Web工程HttpServlet代码:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean reset = false;
if(request.getParameter("reset") != null && request.getParameter("reset").equalsIgnoreCase("true")){
reset = true;
}
HttpSession session = request.getSession();
if(reset){
session.setAttribute("RequestNum", 0);
}
else{
Integer number = (Integer)session.getAttribute("RequestNum");
if(null == number){
number = 0;
}
number = number.intValue() + 1;
session.setAttribute("RequestNum", number);
}
Integer requestNum = (Integer)session.getAttribute("RequestNum");
String outputBody = "Session request number::" + requestNum;
response.getOutputStream().write(outputBody.getBytes());
response.setStatus(200);
}
测试:
Step1,开启182和186上的Tomcat,通过Nginx访问Servlet若干次;
Step2,关闭182上Tomcat,关闭186上Tomcat,通过Nginx访问Servlet若干次;
Step3,关闭186上Tomcat,关闭182上Tomcat,通过Nginx访问Servlet若干次;
结果:
多次的联系访问返回连续的计数结果:
Session request number::4
MSM在Session管理时,Tomcat中会保持本地Session,往Memcached中的同步是异步完成的,所以访问速度和普通模式没什么区别。
唯一有区别的是,操作完Step2/Step3后的首次访问时,响应速度会变慢,测试结果为20ms减慢到350ms,但是后续访问速度恢复正常。