Tomcat通過Redis實現session共享的完整部署記錄

散盡浮華發表於2018-08-27

 

對於生產環境有了一定規模的tomcat叢集業務來說,要實現session會話共享,比較穩妥的方式就是使用資料庫持久化session.為什麼要持久化session(共享session)呢?因為在客戶端每個使用者的Session物件存在Servlet容器中,如果Tomcat伺服器重啟或者當機的話,那麼該session就會丟失,而客戶端的操作會由於session丟失而造成資料丟失;如果當前使用者訪問量巨大,每個使用者的Session裡存放大量資料的話,那麼就很佔用伺服器大量的記憶體,進而致使伺服器效能受到影響。資料庫持久化session,分為物理資料庫和記憶體資料庫。物理資料庫備份session,由於其效能原因,不推薦;記憶體資料庫可以使用redis和memcached,之前已經介紹了memcached方式實現session共享了,下面說下redis方式:

但是有一點需要清楚:就是Redis這種方式目前還暫不支援Tomcat8環境(因為現在網上外掛不支援tomcat8,非要支援tomcat8,則需修改外掛jar包的原始碼)!下面就先說下Tomcat7+Redis+Nginx實現session會話共享的操作記錄:

實現達到的效果
當客戶端訪問Nginx伺服器時,Nginx負載均衡會自動將請求轉發到Tomcat1節點或Tomcat2節點伺服器,以減輕Tomcat壓力,從而達到Tomcat叢集化部署,為了使各Tomcat之間共享同一個Session,將採用Redis快取服務來集中管理Session儲存。Nginx實現負載均衡,並使用Redis實現session共享。本案例採用的是redis單點方式(可以給這個redis節點配置一個從節點,採用redis主從模式,連線redis的master節點.redis預設不支援主主模式),如果使用redis叢集方式,則採用Sentinels連線。

1) 基礎資訊

ip                 主機名           應用                       埠
192.168.10.200     Nginx-node       nginx1.12.2                80
192.168.10.201     Tomcat-node1     java8.131、tomcat7.0.90    8080
192.168.10.202     Tomcat-node2     java8.131、tomcat7.0.90    8080
192.168.10.203     redis-node       redis4.0.1                6379

下面操作在三臺機器上同樣執行:
[root@Nginx-node ~]# cat /etc/redhat-release
CentOS release 6.9 (Final)
    
為了方便測試,關閉iptables防火牆和selinux。如果是生產環境,開啟iptables後,需要開放對應的應用埠。
[root@Nginx-node ~]# setenforce 0
[root@Nginx-node ~]# getenforce
disabled
[root@Nginx-node ~]# cat /etc/sysconfig/selinux |grep "SELINUX=disabled"
SELINUX=disabled
[root@Nginx-node ~]# /etc/init.d/iptables stop

本案例環境部署中所需的軟體下載地址:https://pan.baidu.com/s/1f9GM4iVAzfJsjskpAwv8Og
提取密碼:dsfs
下載到伺服器上的/usr/local/src目錄下.另外:節點伺服器的系統時間一定要保持一致!!

2) 安裝Nginx(在192.168.10.200機器上操作)

[root@Nginx-node ~]# cd /usr/local/src/
[root@Nginx-node src]# ll
total 8920
-rw-rw-r--. 1 root root  981687 Oct 27  2017 nginx-1.12.2.tar.gz
-rw-rw-r--. 1 root root 5453234 Aug 23  2018 openssl-1.1.0i.tar.gz
-rw-rw-r--. 1 root root 2081413 Aug 23  2018 pcre-8.42.tar.gz
-rw-rw-r--. 1 root root  607698 Jan 16  2017 zlib-1.2.11.tar.gz
 
安裝依賴包
[root@Nginx-node src]# yum -y install gcc gcc-c++
 
安裝pcre庫
[root@Nginx-node src]# tar -zvxf pcre-8.42.tar.gz
[root@Nginx-node src]# cd pcre-8.42
[root@Nginx-node pcre-8.42]# ./configure && make && make install
 
安裝zlib庫
[root@Nginx-node pcre-8.42]# cd /usr/local/src/
[root@Nginx-node src]# tar -zvxf zlib-1.2.11.tar.gz
[root@Nginx-node src]# cd zlib-1.2.11
[root@Nginx-node zlib-1.2.11]# ./configure && make && make install
 
安裝openssl
[root@Nginx-node zlib-1.2.11]# cd /usr/local/src/
[root@Nginx-node src]# tar -zvxf openssl-1.1.0i.tar.gz
[root@Nginx-node src]# cd openssl-1.1.0i
[root@Nginx-node openssl-1.1.0i]# ./config && make && make install
 
安裝nginx,特別注意要指定prce zlib openssl原碼包位置
[root@Nginx-node openssl-1.1.0i]# cd /usr/local/src/
[root@Nginx-node src]# tar -zvxf nginx-1.12.2.tar.gz
[root@Nginx-node src]# cd nginx-1.12.2                
[root@Nginx-node nginx-1.12.2]# ./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-pcre=/usr/local/src/pcre-8.42 --with-zlib=/usr/local/src/zlib-1.2.11  --with-openssl=/usr/local/src/openssl-1.1.0i
[root@Nginx-node nginx-1.12.2]# make && make install
 
安裝成功後配置nginx
[root@Nginx-node nginx-1.12.2]# cd /usr/local/nginx/conf/
[root@Nginx-node conf]# cp nginx.conf nginx.conf.bak
[root@Nginx-node conf]# cat nginx.conf
#user  nobody;
worker_processes  8;
  
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
  
#pid        logs/nginx.pid;
  
worker_rlimit_nofile 65535;
events {
   use epoll;
    worker_connections  65535;
}
  
http {
    include       mime.types;
    default_type  application/octet-stream;
    charset utf-8;
          
    ######
    ## set access log format
    ######
    log_format  main  '$http_x_forwarded_for $remote_addr $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_cookie" $host $request_time';
  
    #######
    ## http setting
    #######
    sendfile       on;
    tcp_nopush     on;
    tcp_nodelay    on;
    keepalive_timeout  65;
    fastcgi_connect_timeout 30000;
    fastcgi_send_timeout 30000;
    fastcgi_read_timeout 30000;
    fastcgi_buffer_size 256k;
    fastcgi_buffers 8 256k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
    fastcgi_intercept_errors on;
  
    ##cache##
    client_header_timeout 60s;
    client_body_timeout 60s;
    client_max_body_size 10m;
    client_body_buffer_size 1m;
    proxy_connect_timeout 5;
    proxy_read_timeout 60;
    proxy_send_timeout 5;             
    proxy_buffer_size 64k;
    proxy_buffers 4 128k;
    proxy_busy_buffers_size 128k;
    proxy_temp_file_write_size 1m;
    proxy_temp_path /home/temp_dir;
    proxy_cache_path /home/cache levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30g;
    ##end##
  
    gzip  on;
    gzip_min_length  1k;
    gzip_buffers     4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 9;
    gzip_types       text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php;
    gzip_vary on;
  
    ## includes vhosts
    include vhosts/*.conf;
}
 
[root@Nginx-node conf]# mkdir vhosts
[root@Nginx-node conf]# cd vhosts/
[root@Nginx-node vhosts]# vim lb_tomcat.conf
  upstream tomcat-lb {
      server 192.168.10.201:8080;
      server 192.168.10.202:8080;
      }
                    
      server {
      listen  80;
      server_name www.kevin.com;
      location / {
          proxy_pass http://tomcat-lb;
          proxy_set_header  X-Real-IP $remote_addr;
          proxy_set_header  REMOTE-HOST $remote_addr;
          proxy_set_header  Host $host;
          proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
        }
        location ~ .*\.(gif|jpg|png|htm|html|css|ico|flv|swf)(.*) {
              proxy_pass http://tomcat-lb;
              proxy_redirect off;
              proxy_set_header Host $host;
              proxy_cache cache_one;
              proxy_cache_valid 200 302 1h;
              proxy_cache_valid 301 1d;
              proxy_cache_valid any 10m;
              expires 30d;
              proxy_cache_key $host$uri$is_args$args;
        }
}
 
[root@Nginx-node vhosts]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@Nginx-node conf]# /usr/local/nginx/sbin/nginx
[root@Nginx-node conf]# lsof -i:80
COMMAND   PID   USER   FD   TYPE   DEVICE SIZE/OFF NODE NAME
nginx   25292   root    6u  IPv4 19679665      0t0  TCP *:http (LISTEN)
nginx   25293 nobody    6u  IPv4 19679665      0t0  TCP *:http (LISTEN)
nginx   25294 nobody    6u  IPv4 19679665      0t0  TCP *:http (LISTEN)
nginx   25295 nobody    6u  IPv4 19679665      0t0  TCP *:http (LISTEN)
nginx   25296 nobody    6u  IPv4 19679665      0t0  TCP *:http (LISTEN)
nginx   25297 nobody    6u  IPv4 19679665      0t0  TCP *:http (LISTEN)
nginx   25298 nobody    6u  IPv4 19679665      0t0  TCP *:http (LISTEN)
nginx   25299 nobody    6u  IPv4 19679665      0t0  TCP *:http (LISTEN)
nginx   25300 nobody    6u  IPv4 19679665      0t0  TCP *:http (LISTEN)
 
將域名www.kevin.com解析到192.168.10.200上,訪問http://www.kevin.com,發現訪問請求結果會負載到192.168.10.201和192.168.10.202的tomcat上了。

3)安裝tomcat(在192.168.10.201和192.168.10.202兩臺機器上操作)

安裝java8環境。先解除安裝掉系統自帶的java7,然後安裝java8
[root@Tomcat-node1 ~]# java -version
java version "1.7.0_131"
OpenJDK Runtime Environment (rhel-2.6.9.0.el6_8-x86_64 u131-b00)
OpenJDK 64-Bit Server VM (build 24.131-b00, mixed mode)
[root@Tomcat-node1 ~]# yum -y remove java-1.7.0-openjdk*
[root@Tomcat-node1 ~]# yum -y remove tzdata-java.noarch
[root@Tomcat-node1 ~]# java -version                 
-bash: /usr/bin/java: No such file or directory
   
[root@Tomcat-node1 ~]# ll /usr/local/src/jdk-8u131-linux-x64_.rpm
-rw-rw-r--. 1 root root 169983496 Nov 19  2017 /usr/local/src/jdk-8u131-linux-x64_.rpm
[root@Tomcat-node1 ~]# rpm -ivh /usr/local/src/jdk-8u131-linux-x64_.rpm --force
[root@Tomcat-node1 ~]# vim /etc/profile
......
JAVA_HOME=/usr/java/jdk1.8.0_131
JAVA_BIN=/usr/java/jdk1.8.0_131/bin
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/bin:/sbin/
CLASSPATH=.:/lib/dt.jar:/lib/tools.jar
export JAVA_HOME JAVA_BIN PATH CLASSPATH
   
[root@Tomcat-node1 ~]# source /etc/profile
[root@Tomcat-node1 ~]# java -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
You have new mail in /var/spool/mail/root
   
安裝配置tomcat7
[root@Tomcat-node1 ~]# cd /usr/local/src/
[root@Tomcat-node1 src]# ll apache-tomcat-7.0.90.tar.gz
-rw-rw-r--. 1 root root 9472492 Nov  9  2017 apache-tomcat-7.0.90.tar.gz
[root@Tomcat-node1 src]# tar -zvxf apache-tomcat-7.0.90.tar.gz
[root@Tomcat-node1 src]# mv apache-tomcat-7.0.90 /usr/local/tomcat7
   
配置tomcat7
[root@Tomcat-node1 ~]# cd /usr/local/tomcat7/conf/
[root@Tomcat-node1 conf]# cp server.xml server.xml.bak
[root@Tomcat-node1 conf]# vim server.xml
.......
 <Engine name="Catalina" defaultHost="localhost">                #這一行不需要修改,沒必要動
.......
 <Host name="localhost" 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" />
  </Host>


建立專案目錄
[root@Tomcat-node1 conf]# mkdir -p /data/webapps/{WEB-INF,META-INF,classes,lib}
[root@Tomcat-node1 conf]# mkdir /data/logs

建立測試檔案
[root@Tomcat-node1 ~]# touch /data/webapps/index.jsp 
[root@Tomcat-node1 ~]# vim /data/webapps/index.jsp         
<html>
    <body bgcolor="green">     
    <center>    
    <%=  request.getSession().getId()  %>    
    <h1>192.168.10.201</h1>
    <h1>port:8080</h1>
    <h1>this is Tomcat-node1! </h1> 
    </center>
    </body>
</html>
 
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false"%>
SessionID:<%=session.getId()%><BR>
SessionIP:<%=request.getServerName()%> <BR>
SessionPort:<%=request.getServerPort()%>
<%     out.println("This is Tomcat server 201 !");     %>
You have new mail in /var/spool/mail/root


另一個節點的測試檔案為:
[root@Tomcat-node2 ~]# vim /data/webapps/index.jsp 
<html>
    <body bgcolor="yellow">     
    <center>    
    <%=  request.getSession().getId()  %>    
    <h1>192.168.10.202</h1>
    <h1>port:8080</h1>
    <h1>this is Tomcat-node2! </h1> 
    </center>
    </body>
</html>
 
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false"%>
SessionID:<%=session.getId()%><BR>
SessionIP:<%=request.getServerName()%> <BR>
SessionPort:<%=request.getServerPort()%>
<%     out.println("This is Tomcat server 202 !");     %>


接著配置Redis+Session共享
[root@Tomcat-node1 ~]# cd /usr/local/tomcat7/conf/
[root@Tomcat-node1 conf]# cp context.xml context.xml.bak 
[root@Tomcat-node1 conf]# cat context.xml
......
    <Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />  
    <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"  
             host="192.168.10.203"  
             port="6379"  
             database="0" 
             maxInactiveInterval="60" />


===============================================================
溫馨提示:
如果遠端redis設定了密碼,則就多加一行配置:password="123456"
===============================================================


最後將依賴的三個jar包拷貝到tomcat7的lib目錄下
[root@Tomcat-node1 jar]# pwd
/usr/local/src/tomcat_redis_session/jar
[root@Tomcat-node1 jar]# ll
total 676
-rw-rw-r--. 1 root root 111969 Jul 29  2015 commons-pool2-2.4.2.jar
-rw-rw-r--. 1 root root 553762 Oct 16  2017 jedis-2.9.0.jar
-rw-rw-r--. 1 root root  20241 Aug 27 16:45 tomcat-redis-session-manager1.2.jar
[root@Tomcat-node1 jar]# \cp -rf ./* /usr/local/tomcat7/lib/


啟動tomcat
[root@Tomcat-node1 src]# /usr/local/tomcat8/bin/startup.sh
Using CATALINA_BASE:   /usr/local/tomcat8
Using CATALINA_HOME:   /usr/local/tomcat8
Using CATALINA_TMPDIR: /usr/local/tomcat8/temp
Using JRE_HOME:        /usr/java/jdk1.8.0_131
Using CLASSPATH:       /usr/local/tomcat8/bin/bootstrap.jar:/usr/local/tomcat8/bin/tomcat-juli.jar
Tomcat started.
You have new mail in /var/spool/mail/root
[root@Tomcat-node1 src]# ps -ef|grep tomcat
root      8477     1 87 03:11 pts/0    00:00:03 /usr/java/jdk1.8.0_131/bin/java -Djava.util.logging.config.file=/usr/local/tomcat8/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -classpath /usr/local/tomcat8/bin/bootstrap.jar:/usr/local/tomcat8/bin/tomcat-juli.jar -Dcatalina.base=/usr/local/tomcat8 -Dcatalina.home=/usr/local/tomcat8 -Djava.io.tmpdir=/usr/local/tomcat8/temp org.apache.catalina.startup.Bootstrap start
root      8528  6829  0 03:11 pts/0    00:00:00 grep tomcat
[root@Tomcat-node1 src]# lsof -i:8080
COMMAND  PID USER   FD   TYPE   DEVICE SIZE/OFF NODE NAME
java    8477 root   49u  IPv6 12974768      0t0  TCP *:webcache (LISTEN)

4) redis安裝

[root@redis-node ~]# cd /usr/local/src/
[root@redis-node src]# ll redis-4.0.1.tar.gz 
-rw-rw-r-- 1 root root 1711660 Aug 27 16:19 redis-4.0.1.tar.gz

編寫redis一鍵安裝指令碼
[root@redis-node src]# cat redis_install.sh 
#!/usr/bin/env bash
# It's Used to be install redis.
# Created on 2018/08/27 11:18.
# @author: wangshibo.
# Version: 1.0
   
function install_redis () {
#################################################################################################
        cd /usr/local/src
        tar -zxvf /usr/local/src/redis-4.0.1.tar.gz
        cd redis-4.0.1
        make PREFIX=/usr/local/redis install
        mkdir -p /usr/local/redis/{etc,var}
        rsync -avz redis.conf  /usr/local/redis/etc/
        sed -i 's@pidfile.*@pidfile /var/run/redis-server.pid@' /usr/local/redis/etc/redis.conf
        sed -i "s@logfile.*@logfile /usr/local/redis/var/redis.log@" /usr/local/redis/etc/redis.conf
        sed -i "s@^dir.*@dir /usr/local/redis/var@" /usr/local/redis/etc/redis.conf
        sed -i 's/daemonize no/daemonize yes/g' /usr/local/redis/etc/redis.conf
        sed -i 's/^# bind 127.0.0.1/bind 0.0.0.0/g' /usr/local/redis/etc/redis.conf
 #################################################################################################
}
   
install_redis


賦予指令碼執行許可權,並進行安裝
[root@redis-node src]# chmod 755 /usr/local/src/redis_install.sh
[root@redis-node src]# /bin/bash -x /usr/local/src/redis_install.sh


編寫redis-server啟動指令碼
[root@redis-node src]# cat /etc/init.d/redis-server 
#!/bin/bash
#
# redis - this script starts and stops the redis-server daemon
#
# chkconfig:   - 85 15
# description:  Redis is a persistent key-value database
# processname: redis-server
# config:      /usr/local/redis/etc/redis.conf
# config:      /etc/sysconfig/redis
# pidfile:     /usr/local/redis/var/redis-server.pid
  
# Source function library.
. /etc/rc.d/init.d/functions
  
# Source networking configuration.
. /etc/sysconfig/network
  
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
  
redis="/usr/local/redis/bin/redis-server"
prog=$(basename $redis)
  
REDIS_CONF_FILE="/usr/local/redis/etc/redis.conf"
  
[ -f /etc/sysconfig/redis ] && . /etc/sysconfig/redis
  
lockfile=/var/lock/subsys/redis-server
  
start() {
    [ -x $redis ] || exit 5
    [ -f $REDIS_CONF_FILE ] || exit 6
    echo -n $"Starting $prog: "
    daemon $redis $REDIS_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}
  
stop() {
    echo -n $"Stopping $prog: "
    killproc $prog
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}
  
restart() {
    stop
    start
}
  
reload() {
    echo -n $"Reloading $prog: "
    killproc $redis -HUP
    RETVAL=$?
    echo
}
  
force_reload() {
    restart
}
  
rh_status() {
    status $prog
}
  
rh_status_q() {
    rh_status >/dev/null 2>&1
}
  
case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
        exit 2
esac


賦予指令碼執行許可權,並啟動redis-server
[root@redis-node src]# /etc/init.d/redis-server start
[root@redis-node src]# lsof -i:6379
COMMAND     PID USER   FD   TYPE   DEVICE SIZE/OFF NODE NAME
redis-ser 24439 root    6u  IPv4 24642923      0t0  TCP dns02.kevin.cn:6379 (LISTEN)

溫馨提示:
需要將redis.conf檔案中的bind改為本機ip.不能使用預設的127.0.0.1,否則遠端連線該redis就會失敗
[root@redis-node src]# vim /usr/local/redis/etc/redis.conf
.....
bind 192.168.10.203

重啟redis-server服務
[root@redis-node src]# /etc/init.d/redis-server restart
Stopping redis-server:                                     [  OK  ]
Starting redis-server:                                     [  OK  ]
[root@redis-node src]# lsof -i:6379
COMMAND    PID USER   FD   TYPE   DEVICE SIZE/OFF NODE NAME
redis-ser 8184 root    6u  IPv4 24688720      0t0  TCP dns02.kevin.cn:6379 (LISTEN)

最好在tomcat兩個節點上使用"telnet 192.168.10.203 6379"驗證下redis是否能成功連線

5) tomcat通過redis共享session測試
訪問http://www.kevin.com,不斷重新整理頁面,發現頁面的其他資訊改變,但是sessionid保持不變,即說明實現了session共享!

關閉兩個節點中的任意一個tomcat服務,繼續訪問頁面,發現sessionid任然保持不變!

然後在redis機器上檢視有沒有上面sessionid的key值存在

[root@redis-node ~]# /usr/local/redis/bin/redis-cli -h 192.168.10.203 -p 6379
192.168.10.203:6379> keys *
1) "F7FE0AE8BD1654584A330A804A7BE5FE"
192.168.10.203:6379> 

========================================================================
上面採用的是redis單節點方式(主從模式),如果是redis叢集方式,則採用"Nginx+Tomcat + Redis Sentinel",大致操作如下:

1) 部署Redis+redis叢集,參考文件:https://www.cnblogs.com/kevingrace/p/9004460.html
2) redis叢集方式的session共享配置為(conf/context.xml):
    <Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />
    <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"
             sentinels="192.168.9.223:30001,192.168.9.223:30002" />          #這裡是redis哨兵的地址,多個sentinels叢集就寫多個ip地址
             maxInactiveInterval="60"
             sentinelMaster="mymaster"                                       #這裡是sentinel的master名稱,一定不要寫錯
             password="123456"                                               #還有認證密碼

Tomcat+Redis Sentinel工作原理:
原此時我們連線的不在是redis主從,而是直接連線哨兵,哨兵會監測後端的redis主從,當主掛掉之後,會挑選一臺從當主機,然後在自身的狀態中更新,此時,就不用擔心主掛掉之後,IP飄移的問題了,哨兵可以多個,當某個哨兵掛掉也不會影響。

網路拓撲圖如下:

========================================================================
上面的redis session會話共享方式只適用於tomcat7(現有的外掛不支援tomcat8),如果非要支援tomcat8,則需要稍微改動些原始碼才可以支援了!
tomcat8.5+redis實現session共享所需要的jar包下載地址如下:https://pan.baidu.com/s/10VGLX-Rxuu-gmGuIOskGRQ
提取密碼:tqny

其中:
tomcat-redis-session-manager-master-2.0.0.jar 包的原始碼經過修改,支援tomcat!
本案例使用的是tomcat8.5環境(只要是tomcat8.x版本,都可以!),測試這些jar包,完全可以實現session共享!!!

下載如下三個jar包,放到/usr/local/tomcat8/lib目錄下:
commons-pool2-2.3.jar
jedis-2.7.3.jar
tomcat-redis-session-manager-master-2.0.0.jar

然後修改/usr/local/tomcat8/conf/context.xml檔案,新增如下幾行:

    <Valve className="com.naritech.nicole.gump.RedisSessionHandlerValve" />
    <Manager className="com.naritech.nicole.gump.RedisSessionManager"
        host="192.168.10.203"
        port="6379"
        database="0"
        maxInactiveInterval="60"
     />

案例中配置如下:

[root@Tomcat-node1 ~]# cat /usr/local/tomcat8/conf/context.xml 
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- The contents of this file will be loaded for each web application -->
<Context>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
    <Valve className="com.naritech.nicole.gump.RedisSessionHandlerValve" />
    <Manager className="com.naritech.nicole.gump.RedisSessionManager"
        host="192.168.10.203"
        port="6379"
        database="0"
        maxInactiveInterval="60"
     />
    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
</Context>

重啟tomcat服務

[root@Tomcat-node1 ~]# chmod 755 /usr/local/tomcat8/bin/*
[root@Tomcat-node1 ~]# ps -ef|grep tomcat|awk '{print $2}'|xargs kill -9
[root@Tomcat-node1 ~]# /usr/local/tomcat8/bin/startup.sh                
[root@Tomcat-node1 ~]# lsof -i:8080
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
java    13439 root   50u  IPv6 685905      0t0  TCP *:webcache (LISTEN)

最後訪問http://www.kevin.com頁面,不斷重新整理,發現頁面內容發生改變了,但是sessionid一直不變!說明實現了session共享!!!

相關文章