springboot整合redis实现发布订阅

//监听处理器1
@Bean("messageListener1")
    public MessageListener messageListener1(RedisSerializer<String> redisSerializer) {
        System.out.println("init messageListener1");
        return (message, pattern) -> {
            final byte[] channel = message.getChannel();
            final byte[] body = message.getBody();

            String text = redisSerializer.deserialize(body);
            String topic = redisSerializer.deserialize(channel);
            log.info("client|{},topic|{},text|{}", 1, topic, text);
        };
    }
//监听处理器2
@Bean("messageListener2")
public MessageListener messageListener2(RedisSerializer<String> redisSerializer) {
    System.out.println("init messageListener2");
    return (message, pattern) -> {
        final byte[] channel = message.getChannel();
        final byte[] body = message.getBody();
        String text = redisSerializer.deserialize(body);
        String topic = redisSerializer.deserialize(channel);
        log.info("client|{},topic|{},text|{}", 2, topic, text);
    };
}
  //消息序列化
    @Bean
    public RedisSerializer RedisSerializer() {
        return new StringRedisSerializer();
    }
//redis监听容器
    @Bean("redisMessageListenerContainer")
    RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory, RedisSerializer<String> redisSerializer) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(messageListener1(redisSerializer), new PatternTopic("topic1"));
        container.addMessageListener(messageListener2(redisSerializer), new PatternTopic("topic1"));
        return container;
    }


	@Autowired
    private StringRedisTemplate redisTemplate;
    
    @GetMapping("/publish")
    public RestModel publish() {
        redisTemplate.convertAndSend("topic1", "nijia-倪佳");
        return RestModel.succ();
    }

你可能感兴趣的:(笔记)