Java Architecture train - Implementation of Distributed session with Redis

What is the session

Session is a session on behalf of a client and server interaction, this process can be continuous or may be intermittent. Once the Servlet era (jsp), once the user to interact with the server, the server tomcat will create a session for the user , while the front will have a jsessionid, each interaction will carry. Thus, as long as the server when the user received a request, you can get jsessionid, and find the corresponding session session in memory according to the ID, session after session to get, then we can manipulate the conversation. During the session alive, we think users will be able to use the website has been in a state of being, once the extended session of date, it can be considered that the user has left the site, stop the interaction . User's identity information, we are judged by the session, the session information can be stored for different users.
before presenting the session through the use of monomeric moieties, as follows:

@GetMapping("/setSession")
public Object setSession(HttpServletRequest request) {
    HttpSession session = request.getSession();
    session.setAttribute("userInfo", "new user");
    session.setMaxInactiveInterval(3600);
    session.getAttribute("userInfo");
    // session.removeAttribute("userInfo");
    return "ok";
}

Stateless Session

HTTP requests are stateless, the user initiates multiple requests to the server, the server does not know that many requests are from the same user, this is stateless. the emergence of cookie is to have a state of the user record .
Common, ios interact with the server, and the server interact Andrews, separating the front and rear ends, applets end interact with the service, they are to call interface data by initiating http, each interaction the server will not get the client state, but we can go through processing means, for example, every time a user initiates a request carried a token-userid or the user , this way, you can let the server to obtain the corresponding data based on user id or token. Under each user can be a service request from the same user terminal identification.

Stateful session

Tomcat in the session, it is to have the state, once the user and server interaction, there is a session, the session save the user's information, so that users "have state", and the server and each client will maintain this one relationship, this is managed by the container (ie Tomcat) , this session is a session to save memory space, this way, when different users access the server, you can pass the session to know who is who. tomcat session appear also to allow http requests have become status . If the user is no longer and server interaction, the session timeout disappears, ending his life cycle. In this way, in fact, each user will have a session is maintained, this is a stateful session.
Scene: In traditional project or jsp project is the largest use of all stateful session, there session is to make up for http stateless.

So Cookie is stored in the client's stateful, Session is stored in the server's stateful.

NOTE: tomcat session can be synchronized between multiple means of achieving the system by the state, but the loss will be a certain time, the user requests the event will wait for synchronization, this is undesirable.

Session Architecture

Single Tomcat session

Tomcat first look at a single session, this state is to have the user's first visit to the server, this time the session is generated, and is set into the jsessionid cookie, each subsequent request will carry jsessionid to maintain user state.
Here Insert Picture Description

Static and dynamic separation Session

The server requests the user, since the static and dynamic separation, the front end http request initiated not carry any state, after the first user request, we manually set a token, as the user session, redis placed in such a redis-session, and the token set into the front end of the cookie (app applet or can be placed in the local cache), so the subsequent interaction process, only the front end to the rear end of token passing, the rear end will be able to identify the request from the user who had.

Here Insert Picture Description

Distributed cluster system session

Clustered or distributed systems are essentially multiple systems, it is assumed that there are two server nodes, namely AB system, they can be a cluster, it may also be a distributed system.
As the Session is stored in the server , here we used two servers, two server session is not shared, so a server can not access session to another server.

Here we use Redis implementation of distributed session:
beginning users and A interact with the system, then the user state at this time, we can be saved to redis, as the session information A system, then the user's request into the system B, then B system session and I also redis association, session so the system will unify AB. Of course, as the cookie will carry over user access. Well, this is actually distributed sessions to save the user's status redis.

Here Insert Picture Description

Redis implementing session

Such as when landing registration:

		//实现注册(在数据库里保存用户信息)
        Users userResult = userService.createUser(userBO);
        //创建用户token,存入redis缓存
        UsersVO usersVO = convertUsersVO(userResult);
        //用户token放入cookie
        CookieUtils.setCookie(request, response, "user",
                JsonUtils.objectToJson(usersVO), true);

Redis into the cache code is as follows:

    public UsersVO convertUsersVO(Users userResult) {
    	//产生唯一的token
        String uniqueToken = UUID.randomUUID().toString().trim();
        //将token放入redis缓存
        redisOperator.set(REDIS_USER_TOKEN + ":" + userResult.getId(), uniqueToken);
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(userResult, usersVO);
        usersVO.setUserUniqueToken(uniqueToken);
        return usersVO;
    }

In this way, it is possible to achieve user sessions.

Further SpringBoot also implement user packet sessions:
introducing dependent Spring Session:

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

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>

Configure storage type

spring:
  session:
    store-type: redis
//Application.java
//开启redis作为spring session
@EnableRedisHttpSession  
//去除安全自动装配
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
Published 385 original articles · won praise 326 · views 160 000 +

Guess you like

Origin blog.csdn.net/No_Game_No_Life_/article/details/104314098