Tomcat负载均衡时实现session共享

179 阅读1分钟

使用nginx服务器进行负载均衡

使用nginx的前提 要实现tomcat集群的session共享

在这里插入图片描述

第一步 配置nginx.conf
负载均衡模块用于从”upstream”指令定义的后端主机列表中选取一台主机。
nginx先使用负载均衡模块找到一台主机,再使用upstream模块实现与这台主机的交互。

user root;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream tomcatproxy {
server 192.168.25.100:8080 weight=1 max_fails=1 fail_timeout=20;
server 192.168.25.101:8080 weight=1;
keepalive 16; #最大连接数
}
server {
listen 8888;
server_name localhost;
location /
{
root html;
index index.html;
proxy_pass http://tomcatproxy;
}
}
}

第二步 拷贝tomcat 需要的jar 包到到${TOMCAT_HOME}/lib下

  • tomcat-redis-session-manager.jar
  • jedis-2.5.2.jar
  • commons-pool2-2.2.jar

修改 RedisSessionManager.java initializeSerializer方法(使其支持Tomcat8)

Context context=this.getContext();
if(context!=null)
{
 loader =context.getLoader();
}

第三步:修改tomcat/conf/context.xml配置文件增加Valve,Manager配置。
在context.xml的Context节点下增加如下配置:

<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
<Valve className="com.s.tomcat.redissessions.RedisSessionHandlerValve" />
<Manager className="com.s.tomcat.redissessions.RedisSessionManager"
host="127.0.0.1"
port="6379"
database="0"
password="123456"
maxInactiveInterval="60" />
</Context>

第四步 验证
修改 \webapps\ROOT\index.jsp
添加:

 主机名 Session Id : <%=request.getSession().getId() %>

实现通过nginx转发的同一个请求中的session是同一个(即刷新)
http://192.168.25.100:8888/

在这里插入图片描述在这里插入图片描述

在这里插入图片描述