tomcat結合memcached構建session伺服器

wadeson發表於2017-08-11

memcached伺服器兩臺:192.168.223.136,192.168.223.137

tomcat多例項:192.168.233.146:8081,192.168.223.146:8082

for tomcat configure(這裡使用的tomcat8的版本)

參考:https://github.com/magro/memcached-session-manager/wiki/SetupAndConfiguration

Add memcached-session-manager jars to tomcat

wget http://repo1.maven.org/maven2/de/javakaffee/msm/memcached-session-manager/2.1.1/memcached-session-manager-2.1.1.jar

wget http://repo1.maven.org/maven2/de/javakaffee/msm/memcached-session-manager-tc8/2.1.1/memcached-session-manager-tc8-2.1.1.jar

wget http://repo1.maven.org/maven2/net/spy/spymemcached/2.11.1/spymemcached-2.11.1.jar

下載需要的memcached的三個jar檔案

將這三個jar檔案複製到$CATALINA_HOME/lib/目錄下

由於採用的多例項

export CATALINA_HOME=/usr/local/apache-tomcat-8.5.16
export CATALINA_BASE=/usr/local/tomcat-instance/tomcat1

如果僅僅只是用java來做序列化器只需要這三個包就ok

配置tomcat多例項:

tomcat1的新增配置如下:

<Context path="" docBase="ROOT" reloadable="true">
    <Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
  memcachedNodes="n1:192.168.223.136:11211,n2:192.168.223.137:11211"       這裡的ip就是memcached伺服器的兩個ip
  failoverNodes="n1"
  requestUriIgnorePattern=".*\.(ico|png|gif|jpg|css|js)$"
    />
</Context>

將紅色新增的部分放進各應用程式的context元件內

tomcat2的新增配置和tomcat1一樣:

<Context path="" docBase="ROOT" reloadable="true">
    <Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
  memcachedNodes="n1:192.168.223.136:11211,n2:192.168.223.137:11211"
  failoverNodes="n1"
  requestUriIgnorePattern=".*\.(ico|png|gif|jpg|css|js)$"
     />
</Context>

開啟各自的tomcat的服務

接下來配置memcached伺服器,這裡採用的yum安裝:

yum install memcached -y(兩臺伺服器192.168.223.136,192.168.223.137分別都給裝上)

訪問中可以看見session會話保持已經成功,檢視memcached快取資訊:

[root@wadeson ~]# memcached-tool 127.0.0.1
# Item_Size Max_age Pages Count Full? Evicted Evict_Time OOM
6 304B 553s 1 2 no 0 0 0

 

然後只需要配置前端代理到tomcat即可實現負載均衡

 

另補充:

如果需要採用其他的序列進行session保持:

1、Example for sticky sessions + kryo(需要的包

<Context>
  ...
  <Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
    memcachedNodes="n1:host1.yourdomain.com:11211,n2:host2.yourdomain.com:11211"
    failoverNodes="n1"
    requestUriIgnorePattern=".*\.(ico|png|gif|jpg|css|js)$"
    transcoderFactoryClass="de.javakaffee.web.msm.serializer.kryo.KryoTranscoderFactory"
    />
</Context>

2、
javolution-serializer: msm-javolution-serializerjavolution-5.4.3.

<Context>
 <Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
 memcachedNodes="n1:192.168.1.155:11211,n2:192.168.1.11:11211"
 failoverNodes="n1"
requestUriIgnorePattern=".*\.(ico|png|gif|jpg|css|js)$"
transcoderFactoryClass="de.javakaffee.web.msm.serializer.javolution.javolutionTranscoderFactory"    各個序列器就這裡做了變化

/>
</Context>
3、If you're using Redis, you need the jedis-2.9.0.jar.
更多詳情參考:https://github.com/magro/memcached-session-manager/wiki/SetupAndConfiguration

相關文章