歡迎您光臨本站 註冊首頁

Redis開啟鍵空間通知實現超時通知的步驟詳解

←手機掃碼閱讀     kyec555 @ 2020-06-12 , reply:0

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依賴

  org.springframework.bootspring-boot-starter-data-redis

 

在全域性配置檔案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將監聽redis發出的超時鍵空間通知。

建立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為超時事件

建立listener配置類

  @Configuration  public class RedisListenerConfiguration {     @Bean   public RedisMessageListenerContainer getListenerContainer(RedisConnectionFactory connectionFactory){   //建立連線容器   RedisMessageListenerContainer container = new RedisMessageListenerContainer();   //放入redis連線   container.setConnectionFactory(connectionFactory);   //寫入需要被監聽的型別,即超時監聽   Topic topic = new PatternTopic("__keyevent@0__:expired");   container.addMessageListener(new TopicMessageListener(), topic);   return container;   }  }

 

之後當有鍵值過期時,redis會傳送通知被上面的TopicMessageListener接收,在該類中即可呼叫對應的業務方法進行業務處理。

 


[kyec555 ] Redis開啟鍵空間通知實現超時通知的步驟詳解已經有223次圍觀

http://coctec.com/docs/service/show-post-238226.html