Redis開啟鍵空間通知實現(xiàn)超時通知的步驟詳解
Redis部分設置
修改配置文件redis.conf(Windows為redis.windows.conf)
- 打開該配置文件(位置取決于自己的安裝位置),找到Event notification部分。
- 將notify-keyspace-events Ex的注釋打開或者添加該配置,其中E代表Keyevent,此種通知會返回key的名字,x代表超時事件。
- 如果notify-keyspace-events ""配置沒有被注釋的話要注釋掉,否則不會生效。
- 保存后重啟redis,一定要使用當前配置文件重啟,例如src/redis-server redis.conf
SpringBoot部分設置
添加redis依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
在全局配置文件application中添加redis配置
spring.redis.host = 39.105.145.179 spring.redis.port=6379 spring.redis.database=0 spring.redis.listen-pattern = __keyevent@0__:expired
listen-pattern填寫超時時間,意思為springboot將監(jiān)聽redis發(fā)出的超時鍵空間通知。
創(chuàng)建listener
public class TopicMessageListener implements MessageListener {
@Override
public void onMessage(Message message, byte[] bytes) {
byte[] body = message.getBody();
byte[] channel = message.getChannel();
System.out.println(new String(body));
System.out.println(new String(channel));
}
}
其中message為redis返回的通知,body為超時的key的名字,channel為超時事件
創(chuàng)建listener配置類
@Configuration
public class RedisListenerConfiguration {
@Bean
public RedisMessageListenerContainer getListenerContainer(RedisConnectionFactory connectionFactory){
//創(chuàng)建連接容器
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
//放入redis連接
container.setConnectionFactory(connectionFactory);
//寫入需要被監(jiān)聽的類型,即超時監(jiān)聽
Topic topic = new PatternTopic("__keyevent@0__:expired");
container.addMessageListener(new TopicMessageListener(), topic);
return container;
}
}
之后當有鍵值過期時,redis會發(fā)送通知被上面的TopicMessageListener接收,在該類中即可調用對應的業(yè)務方法進行業(yè)務處理。
總結
到此這篇關于Redis開啟鍵空間通知實現(xiàn)超時通知的步驟的文章就介紹到這了,更多相關redis鍵空間通知內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
redis cluster支持pipeline的實現(xiàn)思路
本文給大家介紹redis cluster支持pipeline的實現(xiàn)思路,在 cluster 上執(zhí)行 pipeline 可能會由于 redis 節(jié)點擴縮容 中途 redirection 切換連接導致結果丟失,具體細節(jié)問題請參考下本文2021-06-06
Redis優(yōu)化token校驗主動失效的實現(xiàn)方案
在普通的token頒發(fā)和校驗中 當用戶發(fā)現(xiàn)自己賬號和密碼被暴露了時修改了登錄密碼后舊的token仍然可以通過系統(tǒng)校驗直至token到達失效時間,所以系統(tǒng)需要token主動失效的一種能力,所以本文給大家介紹了Redis優(yōu)化token校驗主動失效的實現(xiàn)方案,需要的朋友可以參考下2024-03-03
如何在SpringBoot中使用Redis實現(xiàn)分布式鎖
這篇文章主要介紹了如何在SpringBoot中使用Redis實現(xiàn)分布式鎖,在實際開發(fā)中有可能會遇到多個線程同時訪問同一個共享變量,那么上鎖就很重要了,需要的朋友可以參考下2023-03-03

