-
注入监听需要的bean
/** * 消息监听bean注入 * @return */ @Bean MessageListenerAdapter messageListener() { //RedisMsgListener 处理监听消息的逻辑,自定义 return new MessageListenerAdapter( new RedisMsgListener() ); } /** * redis 监听容器实例化bean注入,并指定对应的发布主题 * @param factory 参数 * @return 结果 */ @Bean RedisMessageListenerContainer redisContainer(RedisConnectionFactory factory) { final RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(factory);
//设置订阅的消息主题 container.addMessageListener(messageListener(), new ChannelTopic( "siyuan:websocket:message" )); return container; }
- 监听订阅的消息处理类似 消费者
@Component public class RedisMsgListener implements MessageListener { private static final Logger log = LoggerFactory.getLogger(RedisMsgListener.class); @Override public void onMessage(Message message, byte[] pattern) { log.info("消息订阅成功{}", message); } }
- 消息发布 类似生产者
redisTemplate.convertAndSend("siyuan:websocket:message","发送消息");