spring 使用redis 接管 session

  1. 引入相关依赖
    1. <dependency>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter-redis</artifactId>
    4. </dependency>
    5. <dependency>
    6. <groupId>org.springframework.session</groupId>
    7. <artifactId>spring-session-data-redis</artifactId>
    8. </dependency>

2.增加配置

spring:
  redis:
    host: 192.168.224.65
    port: 6379
    password: 123456
@Configuration
@EnableRedisHttpSession
public class RedisHttpSessionConfig {}

3.设置获取session的值

  @GetMapping("/session/set")
  @ApiOperation("设置session")
  public String set() {
    ServletRequestAttributes attr =
        (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    HttpSession session = attr.getRequest().getSession();

    String key = "test";
    session.setAttribute(key, "jfdksajfklaj");
    return key;
  }

  @GetMapping("/session/get")
  @ApiOperation("获取session")
  public String get(HttpSession session) {
    ServletRequestAttributes attr =
        (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
//    HttpSession session = attr.getRequest().getSession();

    String value = (String) session.getAttribute("test").toString();
    return value;
  }