1.Redis 配置文件修改:
# 开启过期监听(空串关闭)
# notify-keyspace-events ""
notify-keyspace-events Ex
2.新增 RedisConfig 配置:
@Bean
public RedisMessageListenerContainer container (RedisConnectionFactory redisConnectionFactory) {
RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
return redisMessageListenerContainer;
}
3.创建侦听器:
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer);
}
@Override
protected void doRegister(RedisMessageListenerContainer listenerContainer) {
listenerContainer.addMessageListener(this, new PatternTopic("__keyevent@8__:expired"));
}
@Override
public void onMessage(Message message, byte[] pattern) {
String expiredKey = message.toString();
if (expiredKey.contains("test_data:")) {
System.out.println("redis test_data: 过期 key = " + expiredKey);
}
}
}