【Linux学习十】负载均衡带来tomcat的session不一致问题

时间:2021-03-22 20:28:25

环境
  虚拟机:VMware 10
  Linux版本:CentOS-6.5-x86_64
  客户端:Xshell4
  FTP:Xftp4
  tomcat7
  jdk7

session不一致是指web服务器(tomcat等)出现的问题,所以需要针对web容器进行解决。

网络架构如下:

【Linux学习十】负载均衡带来tomcat的session不一致问题
注意关闭11-13的防火墙:service iptables stop

一、使用内存数据库来缓存session
可以使用memcached或者redis

1、192.168.230.11安装memcached
(1)安装memcached
yum install memcached -y

(2)启动memcached
memcached -d -m 128m -p 11211 -l 192.168.230.11 -u root -P /tmp/
-d:后台启动服务
-m:缓存大小
-p:端口
-l:IP
-u:使用那个用户作为管理用户
-P:服务启动后进程文件存放目录

2、配置nginx

worker_processes  ;
events {
worker_connections ;
} http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
access_log logs/access.log main;
sendfile on;
keepalive_timeout ; upstream tom {
server 192.168.230.12:8080;
server 192.168.230.13:8080;
}
server {
listen ;
server_name www.wjy.com;
location / {
root html;
index index.html index.htm;
} location /cat {
proxy_pass http://tom/;
} error_page /50x.html;
location = /50x.html {
root html;
}
}
}

3、192.168.230.12、192.168.230.13配置tomcat
(1)修改tomcat下的context.xml(/usr/local/software/apache-tomcat-7.0.61/conf/context.xml)
在<Context></Context> 里最后面加上下面

<Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
memcachedNodes="n1:192.168.230.11:11211"
sticky="false"
lockingMode="auto"
sessionBackupAsync="false"
requestUriIgnorePattern=".*\.(ico|png|gif|jpg|css|js)$"
sessionBackupTimeout="1000"
transcoderFactoryClass="de.javakaffee.web.msm.serializer.kryo.KryoTranscoderFactory" />

(2)修改index.jsp(/usr/local/apache-tomcat-7.0.61/webapps/ROOT/index.jsp)
192.168.230.12:

from 192.168.230.12
<br/>
SessionId:<%=session.getid()%>

192.168.230.13:

from 192.168.230.13
<br/>
SessionId:<%=session.getid()%>

(3)上传memcached依赖jar(/usr/local/apache-tomcat-7.0.61/lib)

【Linux学习十】负载均衡带来tomcat的session不一致问题

资源链接:

https://download.csdn.net/download/cac2020/10884650

二、tomcat所在集群节点时间必须一致
使用date "+%Y-%m-%d %H:%M:%S"来检查,时间相差很大仍然新生成session

[root@node1 sbin]# date "+%Y-%m-%d %H:%M:%S"
-- ::
[root@node1 sbin]# date -s "2018-12-28 16:49:00"
Fri Dec :: CST
[root@node1 sbin]# date "+%Y-%m-%d %H:%M:%S"
-- ::

验证:

【Linux学习十】负载均衡带来tomcat的session不一致问题

【Linux学习十】负载均衡带来tomcat的session不一致问题

参考:

memcached:
https://blog.csdn.net/qq_24829007/article/details/79393543
https://www.cnblogs.com/interdrp/p/4096466.html
https://blog.csdn.net/a857553315/article/details/80384365

redis:

https://blog.csdn.net/lajigao/article/details/79645057

https://blog.csdn.net/Jack__iT/article/details/80640941

https://github.com/jcoleman/tomcat-redis-session-manager