Linux 下tomcat的session共享(概要和配置文件)

本文涉及的产品
网络型负载均衡 NLB,每月750个小时 15LCU
应用型负载均衡 ALB,每月750个小时 15LCU
简介:

准备条件:

测试服务器192.168.0.2、192.168.0.3、负载均衡设备或配置好的apache、nginx软件等。



1、修改tomcat的conf/server.xml

在<Engine>节点下增加配置,这里直接贴出server.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.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="8006" shutdown="SHUTDOWN">

  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
  <Listener className="org.apache.catalina.core.JasperListener" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html -->
  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container", 
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">
  
    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" 
        maxThreads="150" minSpareThreads="4"/>
    -->
    
    
    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8081" protocol="HTTP/1.1" 
               connectionTimeout="20000" 
               redirectPort="8443" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1" 
               connectionTimeout="20000" 
               redirectPort="8443" />
    -->           
    <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the 
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
    <!--
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8010" protocol="AJP/1.3" redirectPort="8443" />


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">         
    --> 
    <Engine name="Catalina" defaultHost="localhost">

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

          <Manager className="org.apache.catalina.ha.session.BackupManager"
                   expireSessionsOnShutdown="false"
                   notifyListenersOnReplication="true"
                   mapSendOptions="6"/>
          <!--
          <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"
                      port="5000"
                      selectorTimeout="100"
                      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"/>
            <Interceptor className="org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor"/>
          </Channel>

          <Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
                 filter=".*\.gif;.*\.js;.*\.jpg;.*\.png;.*\.htm;.*\.html;.*\.css;.*\.txt;"/>

          <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.ClusterSessionListener"/>
        </Cluster>

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->        

      <!-- The request dumper valve dumps useful debugging information about
           the request and response data received and sent by Tomcat.
           Documentation at: /docs/config/valve.html -->
      <!--
      <Valve className="org.apache.catalina.valves.RequestDumperValve"/>
      -->

      <!-- This Realm uses the UserDatabase configured in the global JNDI
           resources under the key "UserDatabase".  Any edits
           that are performed against this UserDatabase are immediately
           available for use by the Realm.  -->
      <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
             resourceName="UserDatabase"/>

      <!-- Define the default virtual host
           Note: XML Schema validation will not work with Xerces 2.2.
       -->
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"  
               prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>
        -->

    <Context path="" docBase="D:\apache-tomcat-6.0.35\logintest1" reloadable="true" distributable="true" />

      </Host>
    </Engine>
  </Service>
</Server>


2、修改web工程的WEB-INF下的web.xml

对于要进行负载和集群的的应用中的WEB-INF中的web.xml文件要添加如下一句配置
<distributable/>

如下(不过我一般就在tomcat conf下的server.xml的Contex接口中增加属性distributable="true"——上面server.xml中倒数第5行):

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <distributable/>
</web-app>

3、分别启动tomcat,试用自己测试session的demo测试即可。


注意:因为sessionid与访问的域名地址有关,所以测试的时候不要试用2个ip地址访问测试,这样session肯定不一致。

一般我们使用负载均衡设备(F5、netscaler等)或者使用apache、nginx负载均衡软件加在我们集群的tomcat服务器外面,试用一个ip地址分发到不同的tomcat。


备注:

一、

tomcat集群和负载均衡的实现(session同步)补充

因 为tomcat的session同步功能需要用到组播,windows默认情况下是开通组播服务的,但是linux默认情况下并没有开通。

可以通过指令打 开route add -net 224.0.0.0 netmask 240.0.0.0 dev eth0

如果需要服务器启动时即开通组播需在/etc/sysconfig/static-routes文件内加入eht0 net 224.0.0.0 netmask 240.0.0.0。

具体组播概念请查阅CCNP相关内容。


二、

我一般都是引用项目发布(热部署),在server.xml的Context中增加distributable="true",这样工程的web.xml中<distributable/>也可以不加了。

    <Context path="" docBase="D:\apache-tomcat-6.0.35\logintest1" reloadable="true" distributable="true" />

三、

server.xml元素中

            <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
                      address="auto"
                      port="5000"
                      selectorTimeout="100"
                      maxThreads="6"/>

其中address写为auto时,很多时候服务器会自动使用127.0.0.1,这样就会产生问题,所以遇到服务器没有自动读取本地局域网ip的时候,我们手工设置一下,如:192.168.0.2,这样比试用auto保险。


四、

server.xml中我们新增的一些内容部分的具体含义和试用,官方都有说明,参考即可。






相关实践学习
SLB负载均衡实践
本场景通过使用阿里云负载均衡 SLB 以及对负载均衡 SLB 后端服务器 ECS 的权重进行修改,快速解决服务器响应速度慢的问题
负载均衡入门与产品使用指南
负载均衡(Server Load Balancer)是对多台云服务器进行流量分发的负载均衡服务,可以通过流量分发扩展应用系统对外的服务能力,通过消除单点故障提升应用系统的可用性。 本课程主要介绍负载均衡的相关技术以及阿里云负载均衡产品的使用方法。
目录
相关文章
|
4月前
|
Linux 数据安全/隐私保护 Windows
Linux共享Windows目录
Linux共享Windows目录
|
4月前
|
安全 Java 应用服务中间件
Tomcat的配置文件中有哪些关键的配置项,它们分别有什么作用?
日常开发中我们除了 web.xml 文件的配置,server.xml 文件也是 Tomcat 服务器的重要配置文件,本文内容详细介绍各个配置项的用法,结合业务场景来举例说明,让你更清楚各配置项的用法
143 1
|
4月前
|
存储 Ubuntu Linux
在Linux中,如何查看当前主机的主机名,如何修改主机名?要想重启后依旧生效,需要修改哪个配置文件?
在Linux中,如何查看当前主机的主机名,如何修改主机名?要想重启后依旧生效,需要修改哪个配置文件?
|
2月前
|
Java Shell 应用服务中间件
Mac系统下配置环境变量:Javajdk、maven、tomcat 环境变量配置及对应配置文件
这篇文章介绍了如何在Mac系统下配置Java JDK、Maven和Tomcat的环境变量,包括配置文件的选择、解决环境变量在zsh shell中无效的问题、查看和设置系统环境变量的方法,以及JDK和Maven的下载、配置和测试步骤。
1452 1
Mac系统下配置环境变量:Javajdk、maven、tomcat 环境变量配置及对应配置文件
|
2月前
|
XML Java 应用服务中间件
tomcat学习一:tomcat 目录及配置文件学习 server.xml 等
这篇文章是关于Apache Tomcat服务器的目录结构、配置文件(特别是server.xml)的详细介绍和学习指南。
66 0
tomcat学习一:tomcat 目录及配置文件学习 server.xml 等
|
4月前
|
应用服务中间件 Linux iOS开发
使用 setenv 配置文件管理 Tomcat 的自定义环境变量
【8月更文挑战第29天】通过在Tomcat安装目录的`bin`文件夹下创建`setenv.sh`或`setenv.bat`文件,可以轻松管理Tomcat的自定义环境变量。针对Linux/macOS系统,需编辑`setenv.sh`文件,如`export MY_CUSTOM_VAR=&quot;my custom value&quot;`;而在Windows系统中,则编辑`setenv.bat`,如`set MY_CUSTOM_VAR=my custom value`。
213 1
|
4月前
|
应用服务中间件 Linux 网络安全
【Azure 应用服务】App Service for Linux 环境中为Tomcat页面修改默认的Azure 404页面
【Azure 应用服务】App Service for Linux 环境中为Tomcat页面修改默认的Azure 404页面
|
4月前
|
网络协议 安全 应用服务中间件
在Linux中,Tomcat8005、8009、8080三个端口的含义?
在Linux中,Tomcat8005、8009、8080三个端口的含义?
|
4月前
|
缓存 Java 应用服务中间件
在Linux中,Tomcat和Resin有什么区别,工作中怎么选择?
在Linux中,Tomcat和Resin有什么区别,工作中怎么选择?
|
4月前
|
运维 Ubuntu 安全
在Linux中,如何配置NFS共享?
在Linux中,如何配置NFS共享?