前提
-
Redis版本>2.8
-
开启事件通知配置(默认spring session会自动开启该配置)
配置文件:notify-keyspace-events Ex
命令行:redis-cli config set notify-keyspace-events Egx
-
不需要自动开启该配置的话可以将如下配置加入到容器中
@Bean public static ConfigureRedisAction configureRedisAction() { return ConfigureRedisAction.NO_OP; }
- spring boot 自动注入:RedisHttpSessionConfiguration#setImportMetadata方法会注入RedisHttpSessionConfiguration相关配置
- spring session开启redis事件通知相关类: RedisHttpSessionConfiguration、 ConfigureNotifyKeyspaceEventsAction
- spring session自动开启redis事件通知文档
RedisSession监听配置
@Configuration
public class RedisHttpSessionListenerConfig {
/**
* 监听session创建
*/
@EventListener
public void onCreated(SessionCreatedEvent event) {
String sessionId = event.getSessionId();
// spring-session提供的session
Session session = event.getSession();
System.out.println("创建:" + sessionId);
}
/**
* 监听session删除
*/
@EventListener
public void onDeleted(SessionDeletedEvent event) {
String sessionId = event.getSessionId();
// spring-session提供的session
Session session = event.getSession();
System.out.println("删除:" + sessionId);
}
/**
* 监听session过期
*/
@EventListener
public void onExpired(SessionExpiredEvent event) {
String sessionId = event.getSessionId();
// spring-session提供的session
Session session = event.getSession();
System.out.println("过期:" + sessionId);
}
}
原理
- 在spring-Session中session的创建、删除、过期都会接收到redis相关事件的通知
- spring-session中接收到相关通知后再由Spring发布相关ApplicationEvent(SessionCreatedEvent 、SessionDeletedEvent 、SessionExpiredEvent)
- 由spring-context提供的@EventListener注解即可实现相关事件的监听
- Spring Session官方文档
- 将Redis消息转换为Spring的ApplicationEvent实现类:org.springframework.session.data.redis.RedisOperationsSessionRepository
- Redis键空间通知