spring-session装载过程
Session处理流程
- HttpWebHandlerAdapter:spring-web框架入口类
- Session加载过程
- SessionID:由WebSessionIdResolver从cookier获取SessionID
- Session加载:调用Session仓储创建或者从缓存回查Session
- Session保存过程
- Response提交流程中,会调用Session仓储保存Session
PS:spring容器中未加载ReactiveSessionRepository,则spring-web框架会创建默认仓储(ReactiveMapSessionRepository),
相关代码
1、在Spring Boot的配置类上使用 @EnableRedisWebSession注解
- EnableRedisWebSession:REACTIVE模式
- EnableRedisHttpSession:SERVLET模式
@SpringBootApplication(scanBasePackages = {"org.XXXXX"})
@EnableRedisWebSession
public class GateWayApplication {
2、主pom添加依赖
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<version>5.3.5.RELEASE</version>
</dependency>
3、application.yml配置
application.yml只需配置redis配置,不涉及Session配置
redis: host: 127.0.0.1 port: 6379 pool.maxIdle: 10000 pool.minIdle: 1000 pool.maxWaitMillis: 5000 pool.maxTotal: 2 database: 10
4、Session启动
最后笔者写了个Session的GatewayFilterFactory,主要用于
- 启动Session
- 将SessionID回填至cookie
PS:Response提交阶段,Session的save操作,依赖于Session的启动,但笔者在spring框架中未找到相关的节点,因此加入GatewayFilterFactory
WebSession webSession = exchange.getSession() != null ? exchange.getSession().block() : null;
ResponseCookie cookie = null;
if (webSession != null) {
cookie = ResponseCookie.from("SESSION", webSession.getId()).build();
exchange.getResponse().addCookie(cookie);
if (!webSession.isStarted()) {
webSession.start();
}
}