Cache Tomcat session variables

Last Updated: Dec 20, 2017

Tomcat clusters aim to improve load capacity and evenly distribute accesses to different servers. Take the structure framework illustrated in the following figure as an example.

Alibaba Cloud clusters are generally divided into two modes. One is a fully concentrated session where all nodes are kept consistent with each other, and the other is applicable to a single-session where a specific node in a cluster is designated to provide services.

  1. Install Tomcat and JDK for ECS

    Tomcat 7 and JDK 7 are used in this example. We recommend you first download Tomcat to local storage and then upload it to the ECS after configuration is complete.

  2. Tomcat adds Memcached-supported lib package.

    For more information on how to configure memcached-session-manager, see this document.

    Some lib packages are downloaded in this step. The download addresses are provided in the preceding document. Place the downloaded lib packages in the Tomcat/lib directory, as shown in the following figure.

    Note: The prefix of each file msm- does not exist at the beginning. It is added for convenience of management.

    With these packages, you can configure a Tomcat connection to Memcache.

  3. Use Tomcat to synchronize sessions to Memcache.

    This step requires specific Tomcat configuration. Two configuration modes are available: STICKY and NON-STICKY.

    • STICKY: The Server Load Balancer distributes all requests to the same cluster node based on user sessions. All session data is obtained from Tomcat, which backs up a session to Memcache to guarantee high efficiency when obtaining a session.

    • NON-STICKY: The Server Load Balancer distributes requests for every connection separately without considering user sessions. Sessions are all kept in Memcache and all session reads and writes happen in Memcache. This mode requires remote access to data, hence the lower efficiency, but this mode best meets the expected effects of cluster or concentrated cache.

      In /Tomcat/conf/context.xml, edit the configuration for connection to Memcache, and add the following configuration descriptions under the <Context> element. Following are the two Tomcat configuration modes:

      STICKY mode

      1. <Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
      2. memcachedNodes="Memcache address: 11211"
      3. username="Memcache instance name"
      4. password="Memcache password"
      5. memcachedProtocol="binary"
      6. sticky="true"
      7. sessionBackupAsync="true"
      8. sessionBackupTimeout="1000"
      9. requestUriIgnorePattern=".*\.(gif|jpg|jpeg|png|bmp|swf|js|css|html|htm|xml|json)$"
      10. transcoderFactoryClass="de.javakaffee.web.msm.serializer.kryo.KryoTranscoderFactory" ></Manager>

      NON-STICKY mode

      1. <Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
      2. memcachedNodes="Memcache address: 11211"
      3. username="Memcache instance name"
      4. password="Memcache password"
      5. memcachedProtocol="binary"
      6. sticky="false"
      7. lockingMode="auto"
      8. sessionBackupAsync="false"
      9. sessionBackupTimeout="1000"
      10. requestUriIgnorePattern=".*\.(gif|jpg|jpeg|png|bmp|swf|js|css|html|htm|xml|json)$"
      11. transcoderFactoryClass="de.javakaffee.web.msm.serializer.kryo.KryoTranscoderFactory" />

      Note: The memcachedProtocol="binary" setting is required because the attribute value for Tomcat memcached extension mode is text, but Alibaba Cloud only supports binary data.

  4. Modify Tomcat’s JVM settings and NIO.

    1. In the /Tomcat/bin/ directory, modify JVM settings and add the setenv.sh file. Write the configuration to optimize.

      1. CATALINA_OPTS="-server -Xms3072m -Xmx3072m -Xmn1024m -XX:PermSize=96m -XX:MaxPermSize=128m -XX:+UseConcMarkSweepGC -XX:+UseCMSCompactAtFullCollection -XX:CMSMaxAbortablePrecleanTime=50 -XX:+CMSPermGenSweepingEnabled"
    2. In the /Tomcat/conf/context.xml file, modify NIO settings.

      Comment out the original Connector=8080 line and add the following configuration, with NIO mode enabled.

      1. <Connector port="8080"
      2. protocol="org.apache.coyote.http11.Http11NioProtocol"
      3. connectionTimeout="20000"
      4. URIEncoding="UTF-8"
      5. useBodyEncodingForURI="true"
      6. enableLookups="false"
      7. redirectPort="8443" />
  5. Create a JSP for checking sessions.

    Create a JSP file under the Tomcat/webapps/ROOT directory.

    1. <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
    2. <%
    3. String path = request.getContextPath();
    4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    5. %>
    6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    7. <html>
    8. <head>
    9. <base href="<%=basePath%>">
    10. <title>My JSP 'session.jsp' starting page</title>
    11. <meta http-equiv="pragma" content="no-cache">
    12. <meta http-equiv="cache-control" content="no-cache">
    13. <meta http-equiv="expires" content="0">
    14. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    15. <meta http-equiv="description" content="This is my page">
    16. <!--
    17. <link rel="stylesheet" type="text/css" href="styles.css">
    18. -->
    19. </head>
    20. <body>
    21. <h1>
    22. <%
    23. out.println("This is (TOMCAT1), SESSION ID:" + session.getId());
    24. %>
    25. </h1>
    26. </body>
    27. </html>
  6. Upload the ready Tomcat to ECS.

    After the upload starts, you can see your Tomcat: http://yourserver:8080/session.jsp. If the following text is displayed, it indicates that Tomcat has been successfully connected to Memcache.

    1. This is (TOMCAT1), SESSION ID:CAC189E5ABA13FFE29FCB1697F80182B-OCS

Note: Memcache can be used normally for caching Tomcat sessions when the website load is low. When traffic load is high and you are encountering frequent session failures, you must upgrade Memcache rules to restore normal functionality.

Thank you! We've received your feedback.