自定义监听器;
监听到指定库的消息后调用onMessage方法;
可以在该方法里处理接收到的信息
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
@Component
public class RedisListener implements MessageListener {
/**
* 监听到指定数据库的数据的回调方法
*
* @param message
* @param pattern
*/
@Override
public void onMessage(Message message, byte[] pattern) {
System.out.println("监听指定数据库的数据--------------------" + new String(message.getBody(), StandardCharsets.UTF_8));
}
}
设定自定义的监听器只监听redis指定数据库的消息
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
@Component
public class RedisChooseDbListen {
@Autowired
RedisTemplate redisTemplate;
@Bean
@ConditionalOnMissingBean(RedisMessageListenerContainer.class)
public RedisMessageListenerContainer container() {
RedisMessageListenerContainer listenerContainer = new RedisMessageListenerContainer();
listenerContainer.setConnectionFactory(redisTemplate.getConnectionFactory());
//监听指定db0,db1的set事件
listenerContainer.addMessageListener(new RedisListener(), new PatternTopic("__keyevent@1__:set"));
listenerContainer.addMessageListener(new RedisListener(), new PatternTopic("__keyevent@0__:set"));
return listenerContainer;
}
}