Spring Session -- WebSession Integration WebSession 集成
官网:https://spring.io/projects/spring-session
Samples:https://docs.spring.io/spring-session/reference/samples.html#samples
指引
- Spring Session – HttpSession Integration HttpSession集成
- Spring Session – WebSocket Integration WebSocket 集成
- Spring Session – WebSession Integration WebSession 集成
- Spring Session – Spring Security Integration Spring Security 集成
WebSession Integration WebSession 集成
Spring Session 提供了与 Spring WebFlux 支持的透明集成,可以使用 Spring Session 支持的实现切换实现
Java 配置
@EnableRedisWebSession
public class SessionConfiguration {
@Bean
public LettuceConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory();
}
}
- @EnableRedisWebSession 注解
- LettuceConnectionFactory 创建了一个将 Spring Session 连接到 Redis 服务器
工作原理
与 Servlet API 及其 相比,Spring Session 与 Spring WebFlux 及其集成要容易得多。 Spring WebFlux 提供了 WebSessionStore API,它提供了持久化策略
创建一个实现 WebSession 接口的 SpringSessionWebSession 封装(委托给) Spring Session 的 Session
public class SpringSessionWebSession implements WebSession {
enum State {
NEW, STARTED
}
private final S session;
private AtomicReference<State> state = new AtomicReference<>();
SpringSessionWebSession(S session, State state) {
this.session = session;
this.state.set(state);
}
@Override
public void start() {
this.state.compareAndSet(State.NEW, State.STARTED);
}
@Override
public boolean isStarted() {
State value = this.state.get();
return (State.STARTED.equals(value)
|| (State.NEW.equals(value) && !this.session.getAttributes().isEmpty()));
}
@Override
public Mono<Void> changeSessionId() {
return Mono.defer(() -> {
this.session.changeSessionId();
return save();
});
}
// ... other methods delegate to the original Session
}
创建一个实现 WebSessionStore 接口的 SpringSessionWebSessionStore 封装(委托给)ReactiveSessionRepository,SpringSessionWebSession 封装 Session
public class SpringSessionWebSessionStore<S extends Session> implements WebSessionStore {
private final ReactiveSessionRepository<S> sessions;
public SpringSessionWebSessionStore(ReactiveSessionRepository<S> reactiveSessionRepository) {
this.sessions = reactiveSessionRepository;
}
// ...
}
WebSessionManager 封装(委托给) WebSessionStore 和 WebSessionIdResolver 作为一个 Bean 需要注册到 ApplicationContext 中,以便被 Spring WebFlux 检测到
Cookie 序列化器
// tag::webflux-cookie-serializer[]
@Bean
public WebSessionIdResolver webSessionIdResolver() {
CookieWebSessionIdResolver resolver = new CookieWebSessionIdResolver();
resolver.setCookieName("JSESSIONID");
resolver.addCookieInitializer((builder) -> builder.path("/"));
resolver.addCookieInitializer((builder) -> builder.sameSite("Strict"));
return resolver;
}
// end::webflux-cookie-serializer[]
- 将cookie的名称定制为JSESSIONID
- 将cookie的路径定制为/(而不是默认的上下文根目录)
- 将SameSite cookie指令定制为Strict