SpringBoot整合Redis监听Key过期事件
修改 Redis 配置文件
找到 redis.windows.conf 文件,搜索 “notify-keyspace-events”
修改为 “notify-keyspace-events Ex”,这样我们的 Redis 就支持 key 过期事件的监听了
注入redisMessageListenerContainer
在配置类 RedisConfig.java 中注入一个 redisMessageListenerContainer 的Bean 用于监听
@Bean
RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
// 监听所有库的key过期事件
container.setConnectionFactory(connectionFactory);
return container;
}
创建监听类RedisKeyExpirationListener
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
/**
* 监听 Redis key 过期事件
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
public RedisKeyExpirationListener(RedisMessageListenerContainer redisMessageListenerContainer) {
super(redisMessageListenerContainer);
}
/**
* 针对 redis 数据失效事件,进行数据处理
*/
@Override
public void onMessage(Message message, byte[] pattern) {
// 拿到key
log.info("监听Redis key过期,key:{},channel:{}", message.toString(), new String(pattern));
}
}
我们可以监听到过期的 key 的信息,以及通道的信息
操作 API
工具类redisUtils
在 RedisUtils 中加入如下操作
```java
/**
* 写入数据,并设置过期时间
*/
public boolean set(final String key, Object value, long time) {
if (StringUtils.isBlank(key)) {
return false;
}
try {
template.opsForValue().set(key, value, time, TimeUnit.SECONDS);
log.info("存入redis成功,key:{},value:{}", key, value);
return true;
} catch (Exception e) {
log.error("存入redis失败,key:{},value:{}", key, value);
e.printStackTrace();
}
return false;
}
测试用例
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Date;
@SpringBootTest
class RedisTestApplicationTests {
@Autowired
private RedisUtils redisUtil;
@Test
void contextLoads() {
UserInfo userInfo = new UserInfo();
userInfo.setId(1);
userInfo.setName("jack");
userInfo.setCreateTime(new Date());
// 放入redis,并设置过期时间为5秒
redisUtil.set("user", userInfo, 5);
}
}
我们向 Redis 中存入了一个 key 为 “user”,value 为 UserInfo 对象的数据,并设置了过期时间为 5 秒
我们添加一个数据
5秒后…
监听事件
触发了 key 过期事件,这时候,我们拿到过期的 key 就可以对应的做一些业务处理了