springboot 整合 spring session

springboot 整合 spring session

起男 1,635 2020-11-05

springboot 整合 spring session

由于spring session的作用是共享多个项目的session,所有需要准备多个项目

引入依赖

<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>

添加session者

配置文件

server:
  port: 8090
spring:
  redis:
    host: localhost
    port: 6379

编写controller

@RestController
@RequestMapping("session")
public class SessionController {

    @RequestMapping("add/{key}/{value}")
    public String addSession(@PathVariable String key, @PathVariable String value, HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute(key,value);
        return "sessionId:"+session.getId();
    }
}

获取session者

配置文件

server:
  port: 8080

spring:
  redis:
    host: localhost
    port: 6379

编写controller

@RestController
@RequestMapping("session")
public class SessionController {

    @RequestMapping("get/{key}")
    public String getSession(@PathVariable String key, HttpServletRequest request){
        HttpSession session = request.getSession();
        String value = (String) session.getAttribute(key);
        return "session:"+session.getId()+",value:"+value;
    }
}

测试

  1. 添加session: 访问http://localhost:8090/session/add/key1/value1,返回sessionId:de55fb83-c5f2-4b75-9ea9-9fd85282cb75
  2. 获取session:访问 http://localhost:8080/session/get/key1 ,返回session:de55fb83-c5f2-4b75-9ea9-9fd85282cb75,value:value1

其他配置

  • spring.session.store-type:默认配置redis,设置spring session使用什么进行存储
  • spring.session.timeout:设置springsession的过期时间,默认单位为s。可以通过@EnableRedisHttpSession的maxInactiveIntervallnSeconds进行设置
  • spring.session.redis.flush-mode:刷新模式,可以通过@EnableRedisHttpSession的redisFlushMode进行配置
    • on_save:默认值,保存时刷新,即响应结束后刷新
    • immediate:实时刷新
  • spring.session.redis.namespace:默认配置是spring:session,存储session的命名空间。可以通过@EnableRedisHttpSession的redisNamespace进行设置