响应式 Redis 索引配置

要开始使用 Redis 索引 Web 会话支持,您需要向项目中添加以下依赖项

  • 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 会话。现在您的应用程序已配置,您可能希望开始自定义设置

使用 JSON 序列化会话

默认情况下,Spring Session Data Redis 使用 Java 序列化来序列化会话属性。有时这可能会有问题,尤其是当您有多个应用程序使用相同的 Redis 实例但具有相同类的不同版本时。您可以提供一个 RedisSerializer bean 来自定义会话如何序列化到 Redis。Spring Data Redis 提供了 GenericJackson2JsonRedisSerializer,它使用 Jackson 的 ObjectMapper 序列化和反序列化对象。

配置 RedisSerializer
@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 GenericJackson2JsonRedisSerializer(objectMapper());
	}

	/**
	 * Customized {@link ObjectMapper} to add mix-in for class that doesn't have default
	 * constructors
	 * @return the {@link ObjectMapper} to use
	 */
	private ObjectMapper objectMapper() {
		ObjectMapper mapper = new ObjectMapper();
		mapper.registerModules(SecurityJackson2Modules.getModules(this.loader));
		return mapper;
	}

	/*
	 * @see
	 * org.springframework.beans.factory.BeanClassLoaderAware#setBeanClassLoader(java.lang
	 * .ClassLoader)
	 */
	@Override
	public void setBeanClassLoader(ClassLoader classLoader) {
		this.loader = classLoader;
	}

}

上面的代码片段使用了 Spring Security,因此我们正在创建一个自定义的 ObjectMapper,它使用 Spring Security 的 Jackson 模块。如果您不需要 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();
    }

}

监听会话事件

通常,对会话事件作出反应很有价值,例如,您可能希望根据会话生命周期进行某种处理。

您可以配置应用程序监听 SessionCreatedEventSessionDeletedEventSessionExpiredEvent 事件。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
    }

}
© . This site is unofficial and not affiliated with VMware.