tomcat集群 (自带Cluster集群)

时间:2023-03-10 02:19:54
tomcat集群 (自带Cluster集群)

不用借助其他任何工具,tomcat自身就可以实现session共享,实现集群。以下为大概步骤

1,如果是在同一台机器上,请保持多个tomcat端口(一个tomcat对应三个端口)不相同;如果是不同机器则不用考虑端口

2,去掉server.xml中的Cluster的注释(<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>)

3,在发布的web项目的web.xml中<web-app>标签里面添加上<distributable />。

现在启动tomcat,访问http://localhost:8080/TestCluster/test.jsp可以看到一个sessionID,

然后在访问http://localhost:8081/TestCluster/test.jsp可以看到和上一个tomcat的sessionID是相同的,

事实说明tomcat已经可以实现sesion共享了。

这种方式就是有局限:tomcat必须在同一局域网下,web项目名称必须相同

附上网上的经典测试项目:

web.xml

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>TomcatDemo</display-name>
<distributable />
</web-app>

test.jsp

<%@ page contentType="text/html; charset=GBK" %>
<%@ page import="java.util.*" %>
<html><head><title>Cluster App Test</title></head>
<body>
Server Info:
<%
out.println(request.getLocalAddr() + " : " + request.getLocalPort()+"<br>");%>
<%
out.println("<br> ID " + session.getId()+"<br>");
// 如果有新的 Session 属性设置
String dataName = request.getParameter("dataName");
if (dataName != null && dataName.length() > 0) {
String dataValue = request.getParameter("dataValue");
session.setAttribute(dataName, dataValue);
}
out.println("<b>Session 列表</b><br>");
System.out.println("============================");
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value = session.getAttribute(name).toString();
out.println( name + " = " + value+"<br>");
System.out.println( name + " = " + value);
}
%>
<form action="test2.jsp" method="POST">
名称:<input type=text size=20 name="dataName">
<br>
值:<input type=text size=20 name="dataValue">
<br>
<input type=submit>
</form>
</body>
</html>