1.开启过期通知配置
默认 notify-keyspace-events "" 修改为:notify-keyspace-events Ex
2.增加监听类
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
public RedisKeyExpirationListener(
RedisMessageListenerContainer listenerContainer) {
super(listenerContainer);
}
@Override
public void onMessage(Message message, byte[] pattern) {
String expireKey = message.toString();
System.out.println("过期key:" + expireKey);
}
}
@Configuration
public class RedisListenerConfig {
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Bean
public RedisMessageListenerContainer container() {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(redisConnectionFactory);
return container;
}
@Bean
public RedisKeyExpirationListener keyExpirationListener() {
return new RedisKeyExpirationListener(this.container());
}
}
3.执行命令
set name zhangsan
expire name 2 //设置2秒过期
//通知效果如图 RedisKeyExpirationListener.onmessage