The principle of session retention mechanism and the Tomcat session cluster example

Source: Internet
Author: User
Tags nginx host server memory

I. Definition of SESSION

In computer science, especially in a network, a session is a temporary and interactive exchange of information between two or more communication devices or between a computer and a user. The session is established at a certain point in time and then removed at a later point in time. The established communication session can involve multiple messages in each direction. The session is usually stateful, which means that at least one communication section needs to hold state information about the session history so that it can communicate, and in stateless communication, the communication consists of a separate request with response. --wikipedia

Session: In a computer, especially in a network application, it is called "conversation control." The Session object stores the properties and configuration information required for a specific user session. This way, when a user jumps between the application's Web pages, the variables stored in the session object are not lost, but persist throughout the user's session. When a user requests a Web page from an application, if the user does not yet have a session, the Web server automatically creates a Session object. When the session expires or is discarded, the server terminates the session. One of the most common uses of Session objects is to store the user's preferences. For example, if a user indicates that they do not like to view a graphic, they can store the information in the Session object. --Baidu

Second, the role and significance of the session

In Web applications, the HTTP protocol is generally used for communication, but HTTP is a stateless communication protocol, where stateless means that the protocol does not have the ability to remember transactions, and after the end of the session, the server does not know what the client state is. In the early days of the HTTP protocol, the HTTP protocol does not preserve any state information that is accessed by the client in order to ensure the concurrent access processing of the Web. Later, the Keep-alive feature was added to the HTTP protocol, which is a session-hold mechanism that allows the session to be kept for a while, while the user will be able to save resources when the time is accessed again, but keep-alive will not log the user's state. Just keep the connection for a while, and when the user accesses it more than this time period, it will still be treated as a new request. However, there are many scenes in the Web application that need to assign the request to the back-end server according to the user's historical access status, such as login record, shopping cart record, browsing record, etc., the user can not find the previous record is affected user experience, so the cookie and session mechanism is born.

First of all, the cookie, when the user needs to login when accessing www.abc.com, because HTTP is stateless, so the access to www.abc.com/xxx and need to re-login, this is a very headache, the advent of cookies to solve the problem, A cookie can save a user's small amount of information to the user's client locally, which takes the www.abc.com domain name as a global and does not need to be re-logged when the user logs on to all URIs under the domain name. However, the user's local storage size is limited, and it is a security risk to store some private information locally.

How to ensure the user experience, but also to ensure security, this is the meaning of the session, the session is a user state storage mechanism, but unlike the cookie, the session is stored in the back-end server memory. Session in the Web application has a very important meaning, it can be very convenient and very safe control access rights.

Ii. Common session hold mode 1.Session sticky (session sticky)

Session stickiness refers to the user after the first visit to a certain algorithm with which a back-end server binding, generally divided into two kinds:

A.SOUCE_IP: Ip_hash algorithm in Nginx, SH algorithm in LVS

Cookies in the B.cookie:haproxy

2.Session Cluster (Session cluster)

  Session cluster refers to a cluster of back-end servers that share all sessions and do not affect the user experience when a single server fails. This approach is typically used in fewer back-end servers (3-4) because when the server is too large it consumes a lot of IO, which affects cluster performance.

The following is an example of the session retention mechanism described in Tomcat.

1. Achieving the basic

The implementation of the TOMCAT session cluster is to use multicast to share sessions in the cluster, similar to keepalived. Tomcat supports this mechanism, so it's simpler to configure, but it doesn't support too many hosts.

2. Structure and IP assignment

Nginx Host: ip:192.168.29.109

Tomcat host cluster: 192.168.29.107, 192.168.29.132, 192.168.29.110

Installing Nginx and Tomcat, tutorial: https://www.cnblogs.com/readygood/p/9801253.html

Shutting down firewalls and SELinux

1. Configure Nginx
Vim/etc/nginx/nginx.conf #配置主配置文件
upstream Tcsv {#在http模块中插入upstream模块     10.10.  10.130:8080;     10.10. 10.131:8080;     10.10. 10.132:8080;                }
Vim/etc/nginx/conf.d/tomcat.conf #添加虚拟主机
server {        a;        server_name www.ready.com;        Location  / {                proxy_pass http://tcsv;                 }        }
2. Configure Tomcat to create a. JSP test page
mkdir -pv/var/lib/tomcat/webapps/test/{web-inf,meta-inf,classes,lib} #创建jsp文件所需目录
Vim/var/lib/tomcat/webapps/test/index.jsp #创建jsp测试文件, function for session ID monitoring
<%@ page language="Java"%>Head><title>tomcata</title></Head> <body>  "red" >Tomcat.ready.com</font>"Centre"Border="1"> <TR> <td>session id</td> <% session.setattribute ("ready.com","ready.com"); %> <td><%= Session.getid ()%></td> </TR> <TR> <td>created on</td> <td><%= session.getcreationtime ()%></td > </TR> </table> </body>3. Start Nginx and Tomcat and refresh the page (modify hosts to add local parsing)

Different colors for different host responses, we can find that even if the response of the same session ID is different, this indicates that the session mechanism is not turned on (because the front-end nginx scheduling default RR algorithm), even if the same host access will be recognized as a different user.

4. Configuring the Tomcat Cluster service

Tomcat native is supported for this service, so just embed the <Cluster> component in the/etc/tomcat/server.xml, and be aware of the <Cluster> Components can only be used in <Engine> and <Host> . Here are some things to note :

1. The default multicast address is 228.0.0.4

2. The default multicast port is 45564 (port and address together determine cluster members.)

3. The broadcast IP is java.net.InetAddress.getLocalHost (). Gethostaddress ( ) ( Make sure there is no broadcast 127.0.0.1, this is a common mistake )

4. The TCP port that listens for replication messages is the first available server socket in range 4000-4100

5. The listener is configured as Clustersessionlistener

6. Configuration of two interceptors Tcpfailuredetector and messagedispatch15interceptor

VI /etc/tomcat/server.xml
A. Insert the following code into <Engine> or <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=" -"Droptime=" the"/> <receiver classname="Org.apache.catalina.tribes.transport.nio.NioReceiver"Address="192.168.29.132"#填写本机IP地址, the default is autoPort="4000"Autobind=" -"Selectortimeout=" the"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>
B. Copy the default Web. xml file (/etc/tomcat/web.xml) to the pre-created/usr/share/tomcat/webapps/test/web-inf/directory and modify

The Web. xml file is used to initialize configuration information such as Welcome page, servlet, servlet-mapping, filter, listener, boot load level, and so on.

CP /etc/tomcat/web.xml/usr/share/tomcat/webapps/test/web-inf/
Vim/usr/share/tomcat/webapps/test/web-inf/web.xml

Insert Code <distributable/> anywhere within <web-app> , and other Tomcat hosts do the same.

c. Restart the Tomcat service to view the Tomcat status

The following information is shown in the log to indicate that the session shared configuration was successful:

d. Refresh the page to see the change of Session ID

You can see that no matter how the refresh session ID remains unchanged, but the title color will change, indicating no matter how the front-end Nginx scheduling session has not changed.

E. Precautions

1. When inserting <Cluster> components, pay attention to the IP configuration of the address= in <Receiver> , try not to use "auto".

The Gateway of the 2.TOMCAT host must be set correctly, otherwise the multicast information cannot be sent and received.

3. To see similar in the Log [TCP://{192, 168, 107}:4000,{192, 168, 107},4000 Information to indicate that the multicast message was sent successfully, or you can use the tcpdump command to check the status of the broadcast information:

228.0. 0.4

The principle of session retention mechanism and the Tomcat session cluster example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.