1. 程式人生 > >java接收redis過期的

java接收redis過期的

首先需要配置keyExpirationListenerContainer對應的bean;

 @Bean
    //key過期監聽,指定資料庫
    RedisMessageListenerContainer keyExpirationListenerContainer(RedisMessageListener listener) {
        RedisMessageListenerContainer listenerContainer = new RedisMessageListenerContainer();
        listenerContainer.setConnectionFactory(taskConnectionFactory());
        listenerContainer.addMessageListener(listener, new PatternTopic("
[email protected]
" + redisDb + "__:expired")); return listenerContainer; }

具體的PatternTopic配置有很多,我大概看了下,常用的就是"[email protected]" + redisDb + "__:expired"監聽指定資料庫的key過期.
然後還要自己寫個listener,即可以實現MessageListener,也可以繼承MessageListenerAdapter都可以,只監聽key過期都可以沒啥具體區別,繼承的話主要是使用redis作為中介軟體,用來發布訂閱使用的多:

package net.rdd.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.
data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.stereotype.Component; @Component public class RedisMessageListener extends MessageListenerAdapter { //public class RedisMessageListener implements MessageListener { private final Logger log = LoggerFactory.getLogger(getClass()); private final RedisSerializer<String> stringSerializer = new StringRedisSerializer(); @Override //key過期會執行這個方法 public void onMessage(Message message, byte[] pattern) { String key = stringSerializer.deserialize(message.getBody()); System.out.println(key); } }