springboot监听redis过期key代码
时间: 2023-05-22 17:04:44 浏览: 275
可以使用 Spring Data Redis 提供的 @EnableRedisRepositories 注解,同时实现 RedisKeyExpirationListener 接口,并在 @Configuration 类中添加监听器配置。
以下是代码片段示例:
@Configuration
@EnableRedisRepositories
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
public RedisMessageListenerContainer redisContainer() {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(jedisConnectionFactory());
return container;
}
@Bean
RedisKeyExpirationListener keyExpirationListener() {
return new RedisKeyExpirationListener();
}
@Bean
MessageListenerAdapter listenerAdapter(RedisKeyExpirationListener keyExpirationListener) {
return new MessageListenerAdapter(keyExpirationListener);
}
@Bean
RedisMessageListenerContainer keyExpirationContainer(RedisKeyExpirationListener keyExpirationListener, MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(jedisConnectionFactory());
container.addMessageListener(listenerAdapter, new PatternTopic("__keyevent@*:expired"));
return container;
}
private static class RedisKeyExpirationListener implements MessageListener {
@Override
public void onMessage(Message message, byte[] pattern) {
String expiredKey = message.toString();
// 处理过期key逻辑
}
}
}
这里我们定义了一个 RedisContainer 和一个 RedisKeyExpirationListener,然后将 RedisKeyExpirationListener 获取到的过期 key 进行处理。ListenAdapter 和 keyExpirationContainer 主要是为了配置监听器,其中"__keyevent@*:expired"用来监听所有 Redis 中发生的 key 过期事件。
阅读全文