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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM