欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

redis发布订阅模式

程序员文章站 2022-07-05 10:35:23
...

config:

    @Bean
    public MessageListenerAdapter messageListenerAdapter(RedisMsgPubSubListener redisMsgPubSubListener) {
        return new MessageListenerAdapter(redisMsgPubSubListener, "redisMsgPubSubListener");
    }

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory,
                                                                       MessageListenerAdapter messageListenerAdapter) {
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
        redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
        redisMessageListenerContainer.addMessageListener(messageListenerAdapter, new PatternTopic(Constants.REDIS_MESSAGE_KEY));
        return redisMessageListenerContainer;
    }

use:

@Component
public class RedisMsgPubSubListener implements MessageListener {
    private Logger logger = LoggerFactory.getLogger(RedisMsgPubSubListener.class);
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * @param message
     * @param pattern
     * 收到订阅的消息后可进行处理
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        RedisSerializer<?> serializer = redisTemplate.getValueSerializer();
        logger.info("Message receive-->pattern:{},message: {},channel: {}", new String(pattern),
            serializer.deserialize(message.getBody()), new String(message.getChannel()));
    }
}

 

相关标签: java基础 redis