springboot+redis過期事件監(jiān)聽實現(xiàn)過程解析
1 修改 redis.conf配置文件:
K Keyspace events, published with keyspace@ prefix事件
E Keyevent events, published with keyevent@ prefix
g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, …
$ String commands
l List commands
s Set commands
h Hash commands
z Sorted set commands
x Expired events (events generated every time a key expires)
e Evicted events (events generated when a key is evicted for maxmemory)
A Alias for g$lshzxe, so that the “AKE” string means all the events.
redis.conf 的默認的配置是:notify-keyspace-events ""
我們需要改為:notify-keyspace-events Ex
即對應上面的鍵的過期事件。修改玩這個重啟一下redis
2 客戶端來監(jiān)聽redis的過期事件:
@Configuration
public class RedisListenerConfig {
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
return container;
}
}
3.書寫一個監(jiān)聽器
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer);
}
@Override
public void onMessage(Message message, byte[] pattern) {
String expiredKey = message.toString();
log.info("expiredKey========="+expiredKey);
}
4.查詢方法中隨便加了兩個表中的不同id,一個30s,一個27s。
redisUtil.set("UserId"+user.get(0).getId(),user.get(0).getId(),30);
redisUtil.set("UserInfoId"+userInfo.get(0).getId(),userInfo.get(0).getId(),27);
控制臺輸出:

需要注意的是:
過期監(jiān)聽消息中返回的是,過期的鍵的key值,是沒有返回value的
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Springboot項目中運用vue+ElementUI+echarts前后端交互實現(xiàn)動態(tài)圓環(huán)圖(推薦)
今天給大家?guī)硪黄坛剃P于Springboot項目中運用vue+ElementUI+echarts前后端交互實現(xiàn)動態(tài)圓環(huán)圖的技能,包括環(huán)境配置及圓環(huán)圖前端后端實現(xiàn)代碼,感興趣的朋友一起看看吧2021-06-06
java中public class與class的區(qū)別詳解
以下是對java中public class與class的區(qū)別進行了分析介紹,需要的朋友可以過來參考下2013-07-07
Springboot配置Swagger2登錄密碼的實現(xiàn)
本文主要介紹了Springboot配置Swagger2登錄密碼的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03
SpringBoot中使用Guava實現(xiàn)單機令牌桶限流的示例
本文主要介紹了SpringBoot中使用Guava實現(xiàn)單機令牌桶限流的示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-06-06

