Tomcat实现session保持案例
apache: tomcats
(1) apache:
mod_proxy
mod_proxy_http 实现代理
mod_proxy_balancer 实现负载均衡
tomcat:
http connector http连接器
(2) apache:
mod_proxy
mod_proxy_ajp ajp模块
mod_proxy_balancer
tomcat:
ajp connector ajp连接器
(3) apache:
mod_jk
tomcat:
ajp connector
方案一:使用nginx反代用户请求到tomcat:(实现负载均衡和session绑定)
配置hosts文件:
192.168.20.1 node1.lee.com node1
192.168.20.2 node2.lee.com node2
192.168.20.8 node4.lee.com node4
192.168.20.7 node3.lee.com node3
前端nginx配置实现负载均衡:
1.在http上下文定义upstream server
upstream tcsrvs {
ip_hash; 实现session绑定
server node1.lee.com:8080;
server node2.lee.com:8080;
}
2.在server段中调用:
location / {
root /usr/share/nginx/html;
}
location ~* \.(jsp|do)$ {
proxy_pass ;
}
后端两个tomcat配置server.xml:
示例只给了第一台的配置,第二台的只需将所有node1改为node2即可
<Engine defaultHost="node1.lee.com">
<Host appBase="/data/webapps/" unpackWARs="true" autoDeploy="true">
<Context path="" docBase="/data/webapps" reloadable="true">
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="/data/logs"
prefix="web1_access_log" suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
/data/webapps/index.jsp文件:
<%@ page language="java" %>
<%@ page import="java.util.*" %>
<html>
<head>
<title>JSP Test Page</title>
</head>
<body>
<% out.println("Hello, world."); %>
</body>
</html>
方案二:使用httpd反代用户请求到tomcat
前端httpd反代配置:
<proxy balancer://lbcluster1>
BalancerMember :8080 loadfactor=10 route=TomcatA
BalancerMember :8080 loadfactor=10 route=TomcatB
</proxy>
<VirtualHost *:80>
ServerName web1.lee.com
ProxyVia On
ProxyRequests Off
ProxyPreserveHost On
<Proxy *>
Order Deny,Allow
Allow from all
</Proxy>
ProxyPass /status !
ProxyPass / balancer://lbcluster1/
ProxyPassReverse / balancer://lbcluster1/
<Location />
Order Deny,Allow
Allow from all
</Location>
</VirtualHost>
后端tomcat主机配置:此处为node1主机,node2主机设置为 jvmRoute="TomcatB",测试页也做相应替换
<Engine defaultHost="node1.lee.com" jvmRoute="TomcatA"> #jvmRoute为了让前端httpd可以精确识别自己,使用jvmRoute作为标示
编辑测试页面:/data/webapps/index.jsp
<%@ page language="java" %>
<html>
<head><title>TomcatA</title></head>
<body>
<h1><font color="red">TomcatA.lee.com</font></h1>
<table>
<tr>
<td>Session ID</td> <% session.setAttribute("lee.com","lee.com"); %>
<td><%= session.getId() %></td>
</tr>
<tr>
<td>Created on</td>
<td><%= session.getCreationTime() %></td>
</tr>
</table>
</body>
</html>
测试:
发现即便调度到同一主机session也会变,更不用说不调度在同一主机
解决:修改这两行,使用session粘性功能