对于高访问量、高并发量的网站或web应用来说,目前最常见的解决方案应该就是利用负载均衡进行server集群,例如比较流行的nginx+memcache+tomcat。集群之后比如我们有N个Tomcat,用户在访问我们的网站时有可能第一次请求分发到tomcat1下,而第二次请求又分发到了tomcat2下,有过web开发经验的朋友都知道这时session不一致会导致怎样的后果,所以我们需要解决一下多个tomcat之间session共享的问题。
环境准备
首先我们需要下载tomcat,这里我们选择tomcat7的解压缩版:
下载完成后我们新建一个目录叫tomcat_cluster(tomcat集群的意思),直接解压下载好的tomcat,并重命名为tomcat1,可以看到目录结构如下:
准备一个最简单的web项目(在IDE中创建部署,拷贝出来即可),并修改index.jsp的内容如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="https://www.linuxidc.com/<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link type="text/css" href="https://www.linuxidc.com/styles.css">
-->
</head>
<body>
SessionID:<%=session.getId()%>
<BR>
SessionIP:<%=request.getServerName()%>
<BR>
SessionPort:<%=request.getServerPort()%>
<%
out.println("This is Tomcat Server 11111");
%>
</body>
</html>
这样基本工作就做完了,下面需要修改tomcat的配置文件,我们打开conf下的server.xml文件,找到下面这一行:
<Engine defaultHost="localhost">
不需要做任何修改,在这一行的下面加入如下代码:
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
channelSendOptions="8">
<Manager className="org.apache.catalina.ha.session.DeltaManager"
expireSessionsOnShutdown="false"
notifyListenersOnReplication="true"/>
<Channel className="org.apache.catalina.tribes.group.GroupChannel">
<Membership className="org.apache.catalina.tribes.membership.McastService"
address="228.0.0.4"
port="45564"
frequency="500"
dropTime="3000"/>
<Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
address="auto"
port="4000"
autoBind="100"
selectorTimeout="5000"
maxThreads="6"/>
<Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
<Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
</Sender>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/>
</Channel>