redis釋出訂閱模式
阿新 • • 發佈:2020-12-21
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())); } }