Redis 配置
现在你已经配置好应用程序,可能想开始自定义一些内容:
- 我想使用 Spring Boot 属性{spring-boot-ref-docs}/application-properties.html#application-properties.data.spring.data.redis.host[自定义 Redis 配置]
- 我想要帮助选择
RedisSessionRepository或RedisIndexedSessionRepository。 - 我想使用 JSON 序列化会话。
- 我想指定不同的命名空间。
- 我想知道会话何时被创建、删除、销毁或过期。
- 我想查找特定用户的所有会话。
- 我想安全地反序列化 Redis 会话。
- 自定义会话过期存储。
使用 JSON 序列化会话
默认情况下,Spring Session 使用 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);
}
指定不同的命名空间
拥有多个应用程序使用同一个 Redis 实例,这种情况并不少见。因此,Spring Session 使用一个 namespace(默认为 spring:session)来在需要时将会话数据分开。
使用 Spring Boot 属性
你可以通过设置 spring.session.redis.namespace 属性来指定它。
spring.session.redis.namespace=spring:session:myapplication
spring:
session:
redis:
namespace: "spring:session:myapplication"
使用注解的属性
你可以通过在 @EnableRedisHttpSession、@EnableRedisIndexedHttpSession 或 @EnableRedisWebSession 注解中设置 redisNamespace 属性来指定 namespace:
@Configuration
@EnableRedisHttpSession(redisNamespace = "spring:session:myapplication")
public class SessionConfig {
// ...
}
@Configuration
@EnableRedisIndexedHttpSession(redisNamespace = "spring:session:myapplication")
public class SessionConfig {
// ...
}
@Configuration
@EnableRedisWebSession(redisNamespace = "spring:session:myapplication")
public class SessionConfig {
// ...
}
在 RedisSessionRepository 和 RedisIndexedSessionRepository 之间选择
在使用 Spring Session Redis 时,你很可能需要在 RedisSessionRepository 和 RedisIndexedSessionRepository 之间做出选择。两者都是将会话数据存储在 Redis 中的 SessionRepository 接口的实现。不过,它们在会话索引和查询的处理方式上有所不同。
RedisSessionRepository:RedisSessionRepository是一个基本实现,将会话数据存储在 Redis 中而不进行任何额外索引。它使用简单的键值结构来存储会话属性。每个会话被分配一个唯一的会话 ID,会话数据存储在与该 ID 关联的 Redis 键下。当需要检索会话时,存储库使用会话 ID 查询 Redis 以获取关联的会话数据。由于没有索引,基于会话 ID 以外的属性或条件查询会话可能效率较低。RedisIndexedSessionRepository:RedisIndexedSessionRepository是一个扩展实现,为存储在 Redis 中的会话提供索引功能。它在 Redis 中引入额外的数据结构,以基于属性或条件高效查询会话。除了RedisSessionRepository使用的键值结构外,它还维护额外的索引以实现快速查找。例如,它可能基于用户 ID 或最后访问时间等会话属性创建索引。这些索引允许基于特定条件高效查询会话,从而提升性能并支持高级会话管理功能。除此之外,RedisIndexedSessionRepository还支持会话过期和删除。
在 Redis Cluster 中使用 RedisIndexedSessionRepository 时,你必须注意它只订阅集群中某个随机 redis 节点的事件,如果事件发生在不同的节点上,可能会导致某些会话索引未被清理。
配置 RedisSessionRepository
使用 Spring Boot 属性
如果你使用 Spring Boot,RedisSessionRepository 是默认实现。不过,如果你想显式指定它,可以在应用程序中设置以下属性:
spring.session.redis.repository-type=default
spring:
session:
redis:
repository-type: default
使用注解
你可以使用 @EnableRedisHttpSession 注解来配置 RedisSessionRepository:
@Configuration
@EnableRedisHttpSession
public class SessionConfig {
// ...
}
配置 RedisIndexedSessionRepository
使用 Spring Boot 属性
你可以通过在应用程序中设置以下属性来配置 RedisIndexedSessionRepository:
spring.session.redis.repository-type=indexed
spring:
session:
redis:
repository-type: indexed
使用注解
你可以使用 @EnableRedisIndexedHttpSession 注解来配置 RedisIndexedSessionRepository:
@Configuration
@EnableRedisIndexedHttpSession
public class SessionConfig {
// ...
}
监听会话事件
配置好索引存储库后,现在就可以开始监听 SessionCreatedEvent、SessionDeletedEvent、SessionDestroyedEvent 和 SessionExpiredEvent 事件了。在 Spring 中有几种监听应用程序事件的方式,我们将使用 @EventListener 注解。
@Component
public class SessionEventListener {
@EventListener
public void processSessionCreatedEvent(SessionCreatedEvent event) {
// do the necessary work
}
@EventListener
public void processSessionDeletedEvent(SessionDeletedEvent event) {
// do the necessary work
}
@EventListener
public void processSessionDestroyedEvent(SessionDestroyedEvent event) {
// do the necessary work
}
@EventListener
public void processSessionExpiredEvent(SessionExpiredEvent event) {
// do the necessary work
}
}
查找特定用户的所有会话
通过检索特定用户的所有会话,你可以跨设备或浏览器跟踪用户的活动会话。例如,你可以将此信息用于会话管理目的,例如允许用户使特定会话失效或登出,或根据用户的会话活动执行操作。
为此,首先你必须使用索引存储库,然后你可以注入 FindByIndexNameSessionRepository 接口,如下所示:
@Autowired
public FindByIndexNameSessionRepository<? extends Session> sessions;
public Collection<? extends Session> getSessions(Principal principal) {
Collection<? extends Session> usersSessions = this.sessions.findByPrincipalName(principal.getName()).values();
return usersSessions;
}
public void removeSession(Principal principal, String sessionIdToDelete) {
Set<String> usersSessionIds = this.sessions.findByPrincipalName(principal.getName()).keySet();
if (usersSessionIds.contains(sessionIdToDelete)) {
this.sessions.deleteById(sessionIdToDelete);
}
}
在上面的示例中,你可以使用 getSessions 方法查找特定用户的所有会话,使用 removeSession 方法移除用户的特定会话。
配置 Redis Session Mapper
Spring Session Redis 从 Redis 检索会话信息并将其存储在 Map<String, Object> 中。该映射需要经过一个映射过程,转换为 MapSession 对象,然后在 RedisSession 中使用。
用于此目的的默认映射器称为 RedisSessionMapper。如果会话映射中不包含构建会话所需的最小键(如 creationTime),该映射器将抛出异常。缺少所需键的一种可能情况是,在保存过程进行时,会话键被并发删除(通常是由于过期)。发生这种情况是因为使用了 HSET 命令 来设置键内的字段,如果键不存在,该命令会创建它。
如果你想自定义映射过程,可以创建自己的 BiFunction<String, Map<String, Object>, MapSession> 实现,并将其设置到会话存储库中。以下示例展示了如何将映射过程委托给默认映射器,但如果抛出异常,则从 Redis 中删除该会话:
- RedisSessionRepository
- RedisIndexedSessionRepository
- ReactiveRedisSessionRepository
@Configuration
@EnableRedisHttpSession
public class SessionConfig {
@Bean
SessionRepositoryCustomizer<RedisSessionRepository> redisSessionRepositoryCustomizer() {
return (redisSessionRepository) -> redisSessionRepository
.setRedisSessionMapper(new SafeRedisSessionMapper(redisSessionRepository));
}
static class SafeRedisSessionMapper implements BiFunction<String, Map<String, Object>, MapSession> {
private final RedisSessionMapper delegate = new RedisSessionMapper();
private final RedisSessionRepository sessionRepository;
SafeRedisSessionMapper(RedisSessionRepository sessionRepository) {
this.sessionRepository = sessionRepository;
}
@Override
public MapSession apply(String sessionId, Map<String, Object> map) {
try {
return this.delegate.apply(sessionId, map);
}
catch (IllegalStateException ex) {
this.sessionRepository.deleteById(sessionId);
return null;
}
}
}
}
@Configuration
@EnableRedisIndexedHttpSession
public class SessionConfig {
@Bean
SessionRepositoryCustomizer<RedisIndexedSessionRepository> redisSessionRepositoryCustomizer() {
return (redisSessionRepository) -> redisSessionRepository.setRedisSessionMapper(
new SafeRedisSessionMapper(redisSessionRepository.getSessionRedisOperations()));
}
static class SafeRedisSessionMapper implements BiFunction<String, Map<String, Object>, MapSession> {
private final RedisSessionMapper delegate = new RedisSessionMapper();
private final RedisOperations<String, Object> redisOperations;
SafeRedisSessionMapper(RedisOperations<String, Object> redisOperations) {
this.redisOperations = redisOperations;
}
@Override
public MapSession apply(String sessionId, Map<String, Object> map) {
try {
return this.delegate.apply(sessionId, map);
}
catch (IllegalStateException ex) {
// if you use a different redis namespace, change the key accordingly
this.redisOperations.delete("spring:session:sessions:" + sessionId); // we do not invoke RedisIndexedSessionRepository#deleteById to avoid an infinite loop because the method also invokes this mapper
return null;
}
}
}
}
@Configuration
@EnableRedisWebSession
public class SessionConfig {
@Bean
ReactiveSessionRepositoryCustomizer<ReactiveRedisSessionRepository> redisSessionRepositoryCustomizer() {
return (redisSessionRepository) -> redisSessionRepository
.setRedisSessionMapper(new SafeRedisSessionMapper(redisSessionRepository));
}
static class SafeRedisSessionMapper implements BiFunction<String, Map<String, Object>, Mono<MapSession>> {
private final RedisSessionMapper delegate = new RedisSessionMapper();
private final ReactiveRedisSessionRepository sessionRepository;
SafeRedisSessionMapper(ReactiveRedisSessionRepository sessionRepository) {
this.sessionRepository = sessionRepository;
}
@Override
public Mono<MapSession> apply(String sessionId, Map<String, Object> map) {
return Mono.fromSupplier(() -> this.delegate.apply(sessionId, map))
.onErrorResume(IllegalStateException.class,
(ex) -> this.sessionRepository.deleteById(sessionId).then(Mono.empty()));
}
}
}
自定义会话过期存储
由于 Redis 的特性,如果键一直没有被访问,无法保证何时会触发过期事件。更多细节请参阅 Redis 文档关于键过期。
为了缓解过期事件的不确定性,会话还会连同其预计过期时间一起存储。这确保了每个键在预计过期时都能被访问。RedisSessionExpirationStore 接口定义了跟踪会话及其过期时间的通用操作,并提供了清理过期会话的策略。
默认情况下,每次会话过期会被跟踪到最近的分钟。这允许一个后台任务访问可能过期的会话,以确保 Redis 过期事件以更确定的方式触发。
例如:
SADD spring:session:expirations:1439245080000 expires:33fdd1b6-b496-4b33-9f7d-df96679d32fe
EXPIRE spring:session:expirations:1439245080000 2100
后台任务随后会使用这些映射显式请求每个会话过期键。通过访问键而不是删除它,我们确保仅在 TTL 已过期时 Redis 才为我们删除该键。
通过自定义会话过期存储,你可以根据需要更有效地管理会话过期。为此,你应该提供一个 RedisSessionExpirationStore 类型的 bean,Spring Session Data Redis 配置会识别它:
- SessionConfig
import org.springframework.session.data.redis.SortedSetRedisSessionExpirationStore;
@Configuration
@EnableRedisIndexedHttpSession
public class SessionConfig {
@Bean
public RedisSessionExpirationStore redisSessionExpirationStore(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(RedisSerializer.string());
redisTemplate.setHashKeySerializer(RedisSerializer.string());
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.afterPropertiesSet();
return new SortedSetRedisSessionExpirationStore(redisTemplate, RedisIndexedSessionRepository.DEFAULT_NAMESPACE);
}
}
在上面的代码中,使用的是 SortedSetRedisSessionExpirationStore 实现,它使用有序集合来存储会话 ID,并以过期时间作为分数。
我们不会显式删除这些键,因为在某些情况下可能会存在竞态条件,错误地将一个未过期的键识别为已过期。除了使用分布式锁(这会损害性能)之外,无法确保过期映射的一致性。通过简单地访问键,我们确保仅在该键的 TTL 已过期时才移除它。不过,对于你自己的实现,你可以选择最合适的策略。