响应式 Redis 索引配置
要开始使用 Redis 索引 Web Session 支持,你需要向项目添加以下依赖:
- Maven
- Gradle
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
implementation 'org.springframework.session:spring-session-data-redis'
然后将 @EnableRedisIndexedWebSession 注解添加到配置类上:
@Configuration
@EnableRedisIndexedWebSession
public class SessionConfig {
// ...
}
就是这样。你的应用程序现在拥有了由响应式 Redis 支撑的索引 Web Session 支持。现在你已经配置好应用程序,可能想开始自定义一些内容:
- 我想使用 JSON 序列化会话。
- 我想为 Spring Session 使用的键指定不同的命名空间。
- 我想知道 Spring Session 如何清理过期会话。
- 我想更改会话清理的频率。
- 我想接管清理任务。
- 我想监听会话事件。
使用 JSON 序列化会话
默认情况下,Spring Session Data Redis 使用 Java 序列化来序列化会话属性。有时这可能会有问题,尤其是当你有多个应用程序使用同一个 Redis 实例,但这些应用程序中同一类的版本不同时。你可以提供一个 RedisSerializer bean 来自定义会话如何序列化到 Redis 中。Spring Data Redis 提供 GenericJackson2JsonRedisSerializer,它使用 Jackson 的 ObjectMapper 来序列化和反序列化对象。
@Configuration
public class SessionConfig implements BeanClassLoaderAware {
private ClassLoader loader;
/**
* Note that the bean name for this bean is intentionally
* {@code springSessionDefaultRedisSerializer}. It must be named this way to override
* the default {@link RedisSerializer} used by Spring Session.
*/
@Bean
public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
return new JacksonJsonRedisSerializer<>(objectMapper(), Object.class);
}
/**
* Customized {@link JsonMapper} to add mix-in for class that doesn't have default
* constructors
* @return the {@link JsonMapper} to use
*/
private JsonMapper objectMapper() {
return JsonMapper.builder().addModules(SecurityJacksonModules.getModules(this.loader)).build();
}
/*
* @see
* org.springframework.beans.factory.BeanClassLoaderAware#setBeanClassLoader(java.lang
* .ClassLoader)
*/
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.loader = classLoader;
}
}
上面的代码片段使用了 Spring Security,因此我们正在创建一个使用 Spring Security 的 Jackson 模块的自定义 ObjectMapper。如果你不需要 Spring Security Jackson 模块,你可以注入应用程序的 ObjectMapper bean 并像这样使用它:
@Bean
public RedisSerializer<Object> springSessionDefaultRedisSerializer(ObjectMapper objectMapper) {
return new GenericJackson2JsonRedisSerializer(objectMapper);
}
RedisSerializer bean 的名称必须是 springSessionDefaultRedisSerializer,这样它才不会与 Spring Data Redis 使用的其他 RedisSerializer bean 冲突。如果提供了不同的名称,Spring Session 将不会识别它。
指定不同的命名空间
拥有多个应用程序使用同一个 Redis 实例,或者想将会话数据与 Redis 中存储的其他数据分开,这种情况并不少见。因此,Spring Session 使用一个 namespace(默认为 spring:session)来在需要时将会话数据分开。
你可以通过在 @EnableRedisIndexedWebSession 注解中设置 redisNamespace 属性来指定 namespace:
@Configuration
@EnableRedisIndexedWebSession(redisNamespace = "spring:session:myapplication")
public class SessionConfig {
// ...
}
理解 Spring Session 如何清理过期会话
Spring Session 依赖 Redis 键空间事件来清理过期会话。更具体地说,它监听发送到 __keyevent@*__:expired 和 __keyevent@*__:del 通道的事件,并根据被销毁的键解析会话 ID。
举个例子,假设我们有一个 ID 为 1234 的会话,该会话设置为 30 分钟后过期。当到达过期时间时,Redis 会向 __keyevent@*__:expired 通道发送一条消息为 spring:session:sessions:expires:1234 的事件,这就是过期的键。然后 Spring Session 会从该键解析会话 ID(1234),并从 Redis 中删除所有相关的会话键。
完全依赖 Redis 过期的一个问题是,如果键一直没有被访问,Redis 不保证何时会触发过期事件。更多细节请参阅 Redis 文档中的 Redis 如何使键过期。为了规避过期事件不保证发生这一事实,我们可以确保每个键在预计过期时都被访问。这意味着如果键上的 TTL 已过期,当我们尝试访问该键时,Redis 会移除该键并触发过期事件。因此,每次会话过期也会通过将会话 ID 存储在一个按过期时间排序的有序集合中来跟踪。这允许一个后台任务访问可能过期的会话,以确保 Redis 过期事件以更确定的方式触发。例如:
ZADD spring:session:sessions:expirations "1.702402961162E12" "648377f7-c76f-4f45-b847-c0268bb48381"
我们不会显式删除这些键,因为在某些情况下可能会存在竞态条件,错误地将一个未过期的键识别为已过期。除了使用分布式锁(这会损害我们的性能)之外,无法确保过期映射的一致性。通过简单地访问键,我们确保仅在该键的 TTL 已过期时才移除它。
默认情况下,Spring Session 每 60 秒最多检索 100 个过期会话。如果你想配置清理任务的运行频率,请参阅更改会话清理的频率一节。
配置 Redis 发送键空间事件
默认情况下,Spring Session 尝试使用 ConfigureNotifyKeyspaceEventsReactiveAction 配置 Redis 发送键空间事件,该操作可能会将 notify-keyspace-events 配置属性设置为 Egx。但是,如果 Redis 实例已被正确保护,此策略将不起作用。在这种情况下,应在外部配置 Redis 实例,并暴露一个 ConfigureReactiveRedisAction.NO_OP 类型的 Bean 来禁用自动配置。
@Bean
public ConfigureReactiveRedisAction configureReactiveRedisAction() {
return ConfigureReactiveRedisAction.NO_OP;
}
更改会话清理的频率
根据应用程序的需要,你可能想更改会话清理的频率。为此,你可以暴露一个 ReactiveSessionRepositoryCustomizer<ReactiveRedisIndexedSessionRepository> bean 并设置 cleanupInterval 属性:
@Bean
public ReactiveSessionRepositoryCustomizer<ReactiveRedisIndexedSessionRepository> reactiveSessionRepositoryCustomizer() {
return (sessionRepository) -> sessionRepository.setCleanupInterval(Duration.ofSeconds(30));
}
你也可以调用 disableCleanupTask() 来禁用清理任务。
@Bean
public ReactiveSessionRepositoryCustomizer<ReactiveRedisIndexedSessionRepository> reactiveSessionRepositoryCustomizer() {
return (sessionRepository) -> sessionRepository.disableCleanupTask();
}
接管清理任务
有时,默认的清理任务可能无法满足应用程序的需要。你可能想采用不同的策略来清理过期会话。既然你知道会话 ID 存储在键 spring:session:sessions:expirations 下的有序集合中,并按过期时间排序,你可以禁用默认清理任务并提供自己的策略。例如:
@Component
public class SessionEvicter {
private ReactiveRedisOperations<String, String> redisOperations;
@Scheduled
public Mono<Void> cleanup() {
Instant now = Instant.now();
Instant oneMinuteAgo = now.minus(Duration.ofMinutes(1));
Range<Double> range = Range.closed((double) oneMinuteAgo.toEpochMilli(), (double) now.toEpochMilli());
Limit limit = Limit.limit().count(1000);
return this.redisOperations.opsForZSet().reverseRangeByScore("spring:session:sessions:expirations", range, limit)
// do something with the session ids
.then();
}
}
监听会话事件
通常,对会话事件做出反应很有价值,例如,你可能想根据会话生命周期进行某种处理。
你配置应用程序监听 SessionCreatedEvent、SessionDeletedEvent 和 SessionExpiredEvent 事件。在 Spring 中有几种监听应用程序事件的方式,在本例中我们将使用 @EventListener 注解。
@Component
public class SessionEventListener {
@EventListener
public Mono<Void> processSessionCreatedEvent(SessionCreatedEvent event) {
// do the necessary work
}
@EventListener
public Mono<Void> processSessionDeletedEvent(SessionDeletedEvent event) {
// do the necessary work
}
@EventListener
public Mono<Void> processSessionExpiredEvent(SessionExpiredEvent event) {
// do the necessary work
}
}