How to solve the problem of session sharing in a distributed environment

Reprinted from: https://blog.csdn.net/tanjie_123/article/details/53019752

1. What is a session

Session in the computer, especially in network applications, is called "session control". The Session object stores the properties and configuration information required for a specific user session. This way, variables stored in the session object will not be lost when the user jumps between web pages in the application, but persist throughout the user's session.

Second, the cause of session inconsistency

There is no problem with a single tomcat, but now it is a clustered tomcat, so there is a problem of session inconsistency. As shown


3. Solutions

(1) session replication

Session replication of tomcat can realize session sharing

Advantages: No additional development is required, just build a tomcat cluster

Disadvantages: tomcat is a global session replication, the session of each tomcat in the cluster is completely synchronized (that is, it is exactly the same at any time). In large-scale applications, there are too many users and too many tomcats in the cluster, and the global replication of the session will The cluster performance is degraded. Therefore, the number of tomcats should not be too large, and it is better to have less than 5 tomcats.

(2) session binding

When user A accesses the system for the first time, tomcat1 will serve it, then it will still be served by tomcat1 the next time it accesses

(3) Use redis to centrally manage sessions

The user's session can be saved in redis, and every time the user information is queried from redis, the problem of session sharing can be well solved. As shown in the figure:

4. Practical application

(1) User login problem

For large distributed systems, a single sign-on system can be used to log in, in which the user's session is stored in the redis cache system

(2) User SMS verification

When it is necessary to verify the user's short message, call a third-party service to obtain the verification code, you need to save the verification code in the session, and then compare it with the verification code submitted by the user



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325508909&siteId=291194637