Redis distributed Session

Posted by mattcass on Sat, 19 Feb 2022 14:21:56 +0100

Redis distributed Session

Spring-Session

Spring seesion solves the problem of sharing distributed session s.

introduce

Spring Session is one of the projects of spring. GitHub address: https://github.com/spring-pro.

Spring Session provides a perfect solution for creating and managing servlet httpsessions.

function

spring Session provides API s and implementations for managing user Session information. In addition, it provides the following features:

  • Unload the state saved by the session to a specific external session storage summary, such as Redis. They can provide high-quality clusters independent of the application server.
  • Control how sessionids are exchanged between the client and the server, so that it is easy to write a Restful API because it can obtain sessionids from HTTP headers without relying on cookie s.
  • In the processing code of non Web requests, session data can be accessed, such as in the processing code of JMS messages.
  • Support the use of multiple session s on each browser, making it easy to build a richer end-user experience.
  • When users use WebSocket to send requests, they can keep HttpSession active.

rely on

<!-- spring session and redis starter Integration packages are intended for distributed session Administration -->
<dependency>
 <groupId>org.springframework.session</groupId>
 <artifactId>spring-session-data-redis</artifactId>
</dependency>

Entry class or Config

/**
 * @EnableRedisHttpSession Annotation, enable redis centralized session management, and store all sessions in redis
 * maxInactiveIntervalInSeconds: Set Session expiration time
 * After using Redis Session, the server in the original Spring Boot session. The timeout attribute is no longer valid.
 */
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1000*60)
public class RedisSessionConfig  {
}

test

@RestController
public class RedisSessionTest {

 //Sign in
 @RequestMapping("/login")
 public String login(@RequestParam("uname") String uname,
                     @RequestParam("upass") String upass,
                     HttpServletRequest request){
     String msg="logon failure!";

     if (uname!=null && "admin".equals(uname) && "123".equals(upass)){
         User u=new User();
         u.setUname(uname);  u.setUpass(upass);
         request.getSession().setAttribute("user",u);
         msg="login successful!";
     }
     return msg;
 }
 @Value("${server.port}")
 private String port;
 //Get Session
 @GetMapping("getSession")
 public Map<String,Object> getSession(HttpSession session){
     Map<String,Object> map=new HashMap<>();
     map.put("user",session.getAttribute("user"));
     map.put("port",port);
     return map;
 }
}

summary

Start two micro service projects respectively. Test run found.

It is very convenient for springboot to configure session sharing. You only need the enablereredishttpsession annotation.

unscramble

When RedisSession is created, set three variables creationTime, maxinactivitinterval and lastAccessedTime. The default value of maxinactivitval is 1800 seconds, which means that the session has not been used again within 1800s, indicating that the session has expired. Each time a session is accessed, the value of lastAccessedTime will be updated. The expiration calculation formula of the session is: current time - lastAccessedTime > maxinactivitinterval

Get session

The data saved by spring session in redis includes:

  • SET type

    spring:session:expireations:[min]
    

    min indicates the number of minutes elapsed from 0:00 on January 1, 1970. The member of the SET set is expires:[sessionId], indicating that the members will expire in min minutes.

  • String type

    spring:session:sessions:expires:[sessionId]
    

    The TTL of the data represents the remaining time after the sessionId expires, that is, maxinactivitval.

  • Hash type

    spring:session:sessions:[sessionId]
    

    The data saved by session records creationTime, maxinactivity, lastAccessedTime and attribute. The first two data structures are auxiliary data structures for session expiration management.

Topics: Python Java Redis Spring Distribution