Tomcat集群Session会话复制方案
- 一、配置Tomcat
- 二、项目配置与启动配置
一、配置Tomcat
1.进入tomcat官网查找相应tomcat版本的文档,版本不同配置信息也就相应不同。
图中标识2就是tomcat默认的群集配置
2.打开tomcat/config/server.xml配置文件。
在 <Engine name="Catalina" 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.MessageDispatchInterceptor"/></Channel><Valve className="org.apache.catalina.ha.tcp.ReplicationValve"filter=""/><Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/><Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"tempDir="/tmp/war-temp/"deployDir="/tmp/war-deploy/"watchDir="/tmp/war-listen/"watchEnabled="false"/><ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/></Cluster>
3.重要的默认值:
1.组播地址是228.0.0.42.组播端口为45564(端口和地址共同决定集群成员资格。3.广播的IP是java.net.InetAddress.getLocalHost().getHostAddress()(确保广播IP不是127.0.0.1,这是一个常见错误)4.侦听复制消息的TCP端口是范围中的第一个可用服务器套接字(Socket) 4000-41005.配置侦听器 ClusterSessionListener6.配置两个拦截器TcpFailureDetector,MessageDispatchInterceptor
4.注意点:
1.确保web.xml有` <distributable/>`元素2.如果Tomcat实例在同一台机器上运行,要确保Receiver.port 每个实例的属性都是唯一的,在大多数情况下,Tomcat可以通过自动检测4000-4100范围内的可用端口自行解决此问题。3.如果Tomcat部署不同的服务器上时,则address的值应为当前主机的IP地址,port=”4000”即可。4.多个tomcat共享同一个session时,Membership节点的address和port必须一致,一般不会有改动。5.Receiver节点是配置组播接收者,接收地址address和端口port是当前主机的信息,通过这个信息加入群集。6.保证访问域名或url要一致,否则session不共享。http://localhost:8080/demo与http://localhost:8082/demo2不共享session
5.对要集群的tomcat进行如上信息配置
二、项目配置与启动配置
1.基于maven提供的项目模板快速创建一个web项目。
2.修改默认的index.jsp页面,以供区别session共享是否生效.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><title>Tomcat1</title>
</head>
<body>
SessionID:<%=session.getId()%>
<br>
SessionIP:<%=request.getServerName()%>
<br>
SessionPort:<%=request.getServerPort()%>
</body>
</html>
3.在默认提供的web.xml中添加 <distributable/>
(很重要)
<!DOCTYPE web-app PUBLIC"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN""http://java.sun.com/dtd/web-app_2_3.dtd" ><web-app><display-name>Archetype Created Web Application</display-name><distributable/>
</web-app>
4.tomcat启动信息配置
5.查看tomcat启动信息
Tomcat1
Tomcat2
6.浏览器验证