1. 下載並安裝Tomcat,這裡使用Tomcat的6.0.24版本;
2. 修改conf/server.xml檔案,將其中<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>前後的注釋開啟儲存;
3. 建立一個web app,這裡為了簡單使用tomcat內建的examples web app(webapps/examples),修改其中的WEB-INF/web.xml檔案,在其中<display-name>Servlet and JSP Examples</display-name>節點後添加<distributable/>表明此應用與叢集伺服器複製Session;
4. 在examples目錄下建立一個test.jsp檔案,用來測試Cluster中兩個Tomcat使用的Session是同一個Session,並且當其中一個Tomcat修改Session中的值時,第二個Tomcat會同樣得到更新;代碼如下:
<html> <head> <title></title> </head> <body> <% String mydata = request.getParameter("mydata"); if (mydata != null && mydata.length() != 0) { session.setAttribute("mydata", mydata); } out.println("request.getLocalAddr(): " + request.getLocalAddr()); out.println("<br/>"); out.println("request.getLocalPort(): " + request.getLocalPort()); out.println("<br/>"); out.println("Session ID: " + session.getId()); out.println("<br/>"); out.println("mydata: " + session.getAttribute("mydata")); %> <form> <input type=text size=20 name="mydata"> <br> <input type=submit> </form> </body> </html>
5. 複製此Tomcat(假定命名為Tomcat1)完整目錄到別處(假定命名為Tomcat2),然後修改Tomcat2/conf/server.xml檔案中的連接埠(8080 -> 9080,8009 -> 9009,8443 -> 9443)
6. 啟動Tomcat1和Tomcat2,然後分別訪問http://localhost:8080/examples/test.jsp和http://localhost:9080/examples/test.jsp,會發現其中使用的Session ID是同一個Session ID,相應的修改其中一個的值,另外一個Tomcat Session中的值也會改變。