tomcat保持會話的三種方式

前言

    前面的博客介紹瞭如何使用反向代理至tomcat,一方面不讓tomcat直接響應客戶端請求,一方面實現了動靜分離。我們知道在實際生產中後端不可能就只有一臺tomcat server。那麼如何實現tomcat的負載均衡呢?我們先想象一下這個場景,你在家通過撥號上網登錄一個購物網站,經過反向代理後來到第一臺tomcat server。然後你在購物網站逛了半天選中了一個物品加入了你的購物車。突然網絡閃斷,你重新獲取了新的ip,你刷新網頁後,購物車的東西還在。你有沒有想過爲什麼還在,如果代理服務器把你的jsp請求調度到了另一臺tomcat server呢?實際經驗告訴我們,東西依舊會在購物車裏並不會因爲消失。在haproxy裏可以通過cookie來會話綁定,這個cooki是記錄在客戶端上的。http同樣也可以實現會話粘滯。

TOM會話保持的三種方式

    1、session sticky

    2、session cluster

    3、session server

環境準備

    當客戶端請求jsp等動態資源的時候,反向代理至tomcat來處理。如下圖所示。

    547255256d1e649b161a0c3199c91a09.png-wh_

第一種方式:會話粘滯

httpd服務器
]#vim /etc/httpd/conf.d/tomcat.conf  
Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED
<proxy balancer://tcsrvs>
        BalancerMember http://192.168.32.111:8080  
        BalancerMember http://192.168.32.112:8080
        ProxySet lbmethod=byrequests
        ProxySet stickysession=ROUTEID
</Proxy>
<VirtualHost *:80>
        ServerName www.a.com
        ProxyVia On                   <===響應報文中添加via首部 
        ProxyRequests Off             <===關閉正向代理
        ProxyPreserveHost On
        <Proxy *>
            Require all granted       <===centos7之前的版本不用寫授權,包括下面兩個
        </Proxy>
        ProxyPass / balancer://tcsrvs/
        ProxyPa***everse / balancer://tcsrvs/
        <Location />     
            Require all granted
        </Location>
</VirtualHost>
<Location /balancer-manager>          <===啓用管理接口
        SetHandler balancer-manager   <===啓用內建的處理器
        ProxyPass !                   <===不代理,本機提供服務
        Require all granted
</Location>
配置測試頁面
]#mkdir -pv /usr/share/tomcat/webapps/myapp/WEB-INF
]#vim index.jsp            <===第一臺tomcat
<%@ page language="java" %>
<html>
        <head><title>TomcatA</title></head>
        <body>
                <h1><font color="red">TomcatA</font></h1>
                <table align="centre" border="1">
                        <tr>
                                <td>Session ID</td>
                        <% session.setAttribute("tomcat.com","tomcat.com"); %>
                                <td><%= session.getId() %></td>
                        </tr>
                        <tr>
                                <td>Created on</td>
                                <td><%= session.getCreationTime() %></td>
                        </tr>
                </table>
        </body>
</html>
]#vim index.jsp            <===第二臺tomcat
<%@ page language="java" %>
<html>
        <head><title>TomcatA</title></head>
        <body>
                <h1><font color="red">TomcatB</font></h1>
                <table align="centre" border="1">
                        <tr>
                                <td>Session ID</td>
                        <% session.setAttribute("tomcat.com","tomcat.com"); %>
                                <td><%= session.getId() %></td>
                        </tr>
                        <tr>
                                <td>Created on</td>
                                <td><%= session.getCreationTime() %></td>
                        </tr>
                </table>
        </body>
</html>

第二種方法:session cluster。簡單來說,後面的tomcat server構建了一個集羣。會話第一次調度到服務器處理後,會話會同步到所有的tomcat server,從而不管後面再次請求多少次,會話一直保持不變。這裏不涉及調度器的問題,反向代理只需正常提供正常的代理就行。

http只需提供正常的的反向代理
<proxy balancer://tcsrvs>
        BalancerMember http://192.168.32.111:8080  
        BalancerMember http://192.168.32.112:8080
        ProxySet lbmethod=byrequests
</Proxy>
<VirtualHost *:80>
        ServerName www.a.com
        ProxyVia On                   
        ProxyRequests Off             
        ProxyPreserveHost On
        <Proxy *>
            Require all granted       <===centos7之前的版本不用寫授權,包括下面兩個
        </Proxy>
        ProxyPass / balancer://tcsrvs/
        ProxyPa***everse / balancer://tcsrvs/
        <Location />     
            Require all granted
        </Location>
</VirtualHost>

配置tomcat

    1、啓用集羣,將下列配置放置於server.xml的<engine>或<host>中

<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
                 channelSendOptions="8">

          <Manager className="org.apache.catalina.ha.session.DeltaManager"
                   expireSessionsOnShutdown="false"
                   notifyListenersOnReplication="true"/>

          <Channel className="org.apache.catalina.tribes.group.GroupChannel">
            <Membership className="org.apache.catalina.tribes.membership.McastService"
                        address="228.0.0.4"            <===組播地址,可以隨意更改,兩邊保持一致
                        port="45564"
                        frequency="500"
                        dropTime="3000"/>
            <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
                      address="auto"                   <===auto時,會自動解析本地主機名,並解析得出的IP地址作爲使用的地址,一般改成對外提供tomcat服務的地址
                      port="4000"
                      autoBind="100"
                      selectorTimeout="5000"
                      maxThreads="6"/>

            <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
              <Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
            </Sender>
            <Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
            <Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/>
          </Channel>

          <Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
                 filter=""/>
          <Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>

          <Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"
                    tempDir="/tmp/war-temp/"
                    deployDir="/tmp/war-deploy/"
                    watchDir="/tmp/war-listen/"
                    watchEnabled="false"/>

          <ClusterListener className="org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener"/>
          <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
        </Cluster>

    2、配置webapps

            編輯站點下WEB-INF/web.xml,添加<distributable/>元素,可以從默認的web.xml拷貝。

    3、測試

      26a254bd799196ee32ef3690f63f62e7.png-wh_

      5970a321684f9cff4e9acd17be942d72.png-wh_

第三種方法:session server,會話服務器簡單來說就是基於會話的緩存服務器,memcached就是其中之一。memcached是一種高性能、分佈式的內存對象緩存系統。

]#yum install -y memcached
]#yum install -y libmemcached

    需要的工具類庫:1、msm會話管理器

                                2、tomcat版本的另外一部分msm,根據自己tomcat版本選擇

                                3、能夠讓jsp程序驅動能夠連接適配memcached的類庫

    下載地址:https://github.com/magro/memcached-session-manager/wiki/SetupAndConfiguration

        4b340fbb1adde85071c16403684f41b0.png-wh_


      四個流式化工具選一個就可以。

   c40fdcdc943c204512bd7c1b4dd3e9c9.png-wh_

     將下載的jar類庫放到tomcat安裝目錄下的lib目錄中,修改server.xml

<context path="/myapp" docBase="myapp" reloadable="true">
  <Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
    memcachedNodes="m1:192.168.32.111:11211,m2:192.168.32.112:11211"    <===mencached節點
    failoverNodes="m2"                                                  <===備用節點
    requestUriIgnorePattern=".*\.(ico|png|gif|jpg|css|js)$"
    transcoderFactoryClass="de.javakaffee.web.msm.serializer.javolution.javolutionTranscoderFactory"    <===javolution.javolutionTranscoderFactory名字根據自己選擇的工具更改
    />
</Context>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章