SpringBoot监听Redis的Key过期事件

原文:https://springboot.io/t/topic/24

在一些业务场景中,我们希望在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());
}
}
往Redis写入一个key,并且设置过期时间

 

 


过期事件被触发

 

 


 


————————————————
版权声明:本文为CSDN博主「、YongTing」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_38261597/article/details/89203525

posted @ 2021-04-27 13:46  疯子110  阅读(1096)  评论(0编辑  收藏  举报