tomcat保持會話的三種方式

前言css

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

TOM會話保持的三種方式java

    一、session stickygit

    二、session clustergithub

    三、session serverweb

環境準備apache

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

    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,從而無論後面再次請求多少次,會話一直保持不變。這裏不涉及調度器的問題,反向代理只需正常提供正常的代理就行。centos

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

    一、啓用集羣,將下列配置放置於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>

    二、配置webapps

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

    三、測試

      26a254bd799196ee32ef3690f63f62e7.png-wh_

      5970a321684f9cff4e9acd17be942d72.png-wh_

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

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

    須要的工具類庫:一、msm會話管理器

                                二、tomcat版本的另一部分msm,根據本身tomcat版本選擇

                                三、可以讓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>
相關文章
相關標籤/搜索