监听Redis 缓存过期(Key 失效)事件
1.修改config配置
因为事件通过 Redis 的订阅与发布功能(pub/sub)来进行分发, 所以需要开启 redis 的事件监听与发布
打开 notify-keyspace-events Ex 的注释,开启过期通知功能
2.重启redis , 即可测试失效事件的触发, 监听获取的值为 key
3.进入redis-client
docker exec -it 容器id redis-cli #调用客户端
4.进入监听
PSUBSCRIBE __keyevent@*__:expired
5.再打开一个 redis-client,发送过期数据
setex test 2 2
6.返回之前的 client,监听到过期事件
redis 环境配置完毕;
springboot集成
- yml配置
spring:
redis:
host: xx.xxx.xx.xx
password: xxxx
port: 6379
database: 6
- 配置 redis 远程监听配置:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
/**
* Description: redis 远程监听
* User: liw
* Date: 2023-05-20
*/
@Configuration
public class RedisListenerConfig {
@Bean
RedisMessageListenerContainer listenerContainer(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer listenerContainer = new RedisMessageListenerContainer();
listenerContainer.setConnectionFactory(connectionFactory);
return listenerContainer;
}
@Bean
KeyExpirationEventMessageListener redisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
return new RedisKeyExpirationListener(listenerContainer);
}
}
3.服务端配置监听事件:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Service;
/**
* Description: Redis超时监听器
* User: liw
* Date: 2023-05-20
*/
@Service
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
private static Logger log = LoggerFactory.getLogger(RedisKeyExpirationListener.class);
public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer);
}
@Override
public void onMessage(Message message, byte[] pattern) {
//获取过期的key
String expireKey = message.toString();
log.debug("失效+key is:"+ expireKey);
System.out.println(expireKey);
//这里还可以根据key的自定义前缀来判断执行哪个条件
//......
}
}
4.启动项目,当我们再次通过 redis-client 进行测试;可以看到 console打印一下日志