SpringBoot监听Redis的Key过期事件
在一些业务场景中,我们希望在
Redis
的key过期时,得到通知。
Redis的配置
- 修改
conf
文件 notify-keyspace-events "Ex"
- 该配置表示监听key的过期事件,默认未开启
- 该配置的其他信息(可以监听N多事件),可以参阅配置文件的注释,非常详细
自定义监听器
该监听器会在
key
过期时候触发
import java.nio.charset.StandardCharsets;
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;
public class KeyExpiredListener extends KeyExpirationEventMessageListener {
private static final Logger LOGGER = LoggerFactory.getLogger(KeyExpiredListener.class);
public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer);
}
@Override
public void onMessage(Message message, byte[] pattern) {
String channel = new String(message.getChannel(),StandardCharsets.UTF_8);
//过期的key
String key = new String(message.getBody(),StandardCharsets.UTF_8);
LOGGER.info("redis key 过期:pattern={},channel={},key={}",new String(pattern),channel,key);
}
}
@Confiugration配置
import org.springframework.beans.factory.annotation.Autowired;
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.RedisMessageListenerContainer;
import io.javaweb.redis.listener.KeyExpiredListener;
@Configuration
public class RedisConfiguration {
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Bean
public RedisMessageListenerContainer redisMessageListenerContainer() {
RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
return redisMessageListenerContainer;
}
@Bean
public KeyExpiredListener keyExpiredListener() {
return new KeyExpiredListener(this.redisMessageListenerContainer());
}
}