【Linux學習十】負載均衡帶來tomcat的session不一致問題
環境
虛擬機器:VMware 10
Linux版本:CentOS-6.5-x86_64
客戶端:Xshell4
FTP:Xftp4
tomcat7
jdk7
session不一致是指web伺服器(tomcat等)出現的問題,所以需要針對web容器進行解決。
網路架構如下:
注意關閉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 1; events { worker_connections 1024; } 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_timeout0; upstream tom { server 192.168.230.12:8080; server 192.168.230.13:8080; } server { listen 80; server_name www.wjy.com; location / { root html; index index.html index.htm; } location /cat { proxy_pass http://tom/;} error_page 500 502 503 504 /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)
資源連結:
https://download.csdn.net/download/cac2020/10884650
二、tomcat所在叢集節點時間必須一致
使用date "+%Y-%m-%d %H:%M:%S"來檢查,時間相差很大仍然新生成session
[[email protected] sbin]# date "+%Y-%m-%d %H:%M:%S" 2018-12-29 00:46:03 [[email protected] sbin]# date -s "2018-12-28 16:49:00" Fri Dec 28 16:49:00 CST 2018 [[email protected] sbin]# date "+%Y-%m-%d %H:%M:%S" 2018-12-28 16:49:06
驗證:
參考:
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