Understand distributed session

Hello everyone, I am a CRUD engineer here again. Recently, one of my colleagues suddenly looked at distributed Seesionissues, and then the two of us discussed with each other. Today I want to Sessionsort out the distributed knowledge points. .

In many systems, the user's login function is Sessionused to realize the user's login function. The client fills in the user name and password, sends a request, and the server creates Sessionand returns the current Sessioncorresponding one after receiving the request JessionId, which is stored in the browser cookie. When the client calls other methods to send a request to the server, it will carry it JessionId. After receiving the request, the server verifies Sessionwhether it exists and then determines whether the user is logged in.

In a distributed environment, Sessionproblems will arise. If the server is deployed on two servers A and B

When the user logs in, the request falls on server A. Server A creates a request Sessionand returns it JessionId;

When the user obtains personal information, the request falls on Server B, and the corresponding information carried in the request cannot JesssionIdbe found on Server B.Session

At this time, server B will return an abnormal reminder to the client (the user is not logged in), and the client will receive the return value, and the user will find that he is redirected to the login interface by T again.

SessionNext, let’s look at how to achieve consistency in a distributed environment

1. Client storage

Since in a distributed environment, multiple requests from a client may land on multiple servers, can we change the strategy and store the Sessioninformation directly on the client?
The answer is of course yes. The server Sessionstores the information directly in the server cookie, which ensures Sessionthe consistency of the server. However, we do not recommend doing this, which will cause data security risks, because storing some information in the server is cookieequivalent to This information is exposed to the client, which poses serious security risks.

shortcoming

  • System security issues
  • Cookies have restrictions on data type and data size

2. Session copy

Copy server A's Sessionto server B, and also Sessioncopy server B's to server A, so that the two servers Sessionare consistent. Like tomcatother web containers, they all support Sessionthe replication function. In the same LAN, one server Sessionwill broadcast to other servers.
Insert image description here

shortcoming

  • If there are too many servers in the same network segment, each server will copy the session, which will cause a waste of server memory.

3. Session stickiness

Use Nginxthe server's reverse proxy to proxy server A and server B, and then use ip_hashthe load strategy to bind the client and server, that is to say, client A accesses server B for the first time, then the second time The access must also be to server B, so there will be no Sessioninconsistency problem.

Insert image description here
shortcoming

  • If server A goes down, client A and client B Sessionwill be lost, and all requests from clients A and B will fail.

4. Session centralized management

SessionThis method is to manage all servers in a unified manner, and can use redisother high-performance servers for centralized management Session, and spring officially provides spirng-sessionthis way to deal with Sessionconsistency issues. SessionThis is also a distributed solution currently used by many enterprises .

Insert image description here

spring-session actual combat

SpringProvides Sessiona solution for dealing with distribution - Spring Session. Spring SessionProvides APIs and implementations for managing user sessions.

Spring SessionProvides support for commonly used repositories such as redis, mongodb, , etc., and provides transparent integration with , which means that developers can switch implementations using supported implementations .mysqlSpring SessionHttpSessionSpring SessionHttpSession

Spring SessionI found an implementation flow chart on the Internet
Insert image description here
Spring Sessionand added a SessionRepositoryFilterfilter to modify the packaging request and response. The packaged request is, when the method is SessionRepositoryRequestWrappercalled, it is actually called .getSession()Spring SessionSession

Spring SessionIt is very simple to use. After adding the relevant dependencies, HttpSessionthe effect can be achieved by direct operation.

pom.xml

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>

yml

spring:
  session:
  	# session 失效时间(分钟)
    timeout: 86400
    # session 使用redis存储  
    store-type: redis
    # redis 配置
  redis:
  	# redis 端口号
    port: 6379
    # redis 服务器地址
    host: localhost
    # redis库
    database: 0
    # redis 密码
    password: 123456

Use session

public String test( HttpServletRequest request){
    
    
    HttpSession session = request.getSession();
    session.setAttribute("key_big_handsome","value:it is me");
    return session.getAttribute("key_big_handsome").toString();
}

After executing this method, we look at redis
Insert image description here

  • The first one is used to represent Sessionexpiration in Redis. This kv does not store any useful data, it is just Sessionset to represent expiration. RedisThe expiration time of this key in is Sessionthe expiration interval.
  • The second one that stores this Sessionid is a Settype of Redisdata structure. The last 1681633260000 value in this key is a timestamp calculated based on the Session expiration moment rolled to the next minute.
  • The third one is used to store Sessiondetailed information, including Sessionexpiration interval, latest access time, attributesetc.

Spring SessionThere is a timed task in , every full minute will query the expiration in the corresponding spring:session:expirations:full minute timestamp SessionId, and then visit this again SessionId, that is spring:session:sessions:expires:SessionId, so that the key expiration event can be Redisgenerated in time—that is, Sessionthe expiration event.

Guess you like

Origin blog.csdn.net/qq_43649799/article/details/130169056