新建两个订阅监听

@Component
public class MessageSubListener implements MessageListener {
    @Override
    public void onMessage(Message message, byte[] pattern) {
        System.out.println("consume1: " + new String(message.getBody()) + ", pattern: "+new String(pattern));
    }
}
@Component
public class MessageSubListener2 implements MessageListener {
    @Override
    public void onMessage(Message message, byte[] pattern) {
        System.out.println("consume2: " + new String(message.getBody()));
    }
}

订阅配置

@Configuration
public class RedisSubConfig {
    public static final String SUB_KEY = "message:pool";

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter,
                                            MessageListenerAdapter listenerAdapter2){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic(SUB_KEY));
        container.addMessageListener(listenerAdapter2, new PatternTopic(SUB_KEY));
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(MessageSubListener redisPubSubListener){
        System.out.println("listenerAdapter register");
        return new MessageListenerAdapter(redisPubSubListener, "onMessage");
    }

    @Bean
    MessageListenerAdapter listenerAdapter2(MessageSubListener2 redisPubSubListener){
        System.out.println("listenerAdapter2 register");
        return new MessageListenerAdapter(redisPubSubListener, "onMessage");
    }
}

订阅模块已经写好,然后就是广播消息

@Component
public class PubMessageTask implements ApplicationRunner {
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        for (int i = 0;i< 10; i++){
            redisTemplate.convertAndSend(RedisSubConfig.SUB_KEY, "message:" + i);
            Thread.sleep(1000);
        }
    }
}

测试结果

consume1: message:0, pattern: message:pool
consume2: message:0
consume1: message:1, pattern: message:pool
consume2: message:1
consume1: message:2, pattern: message:pool
consume2: message:2
consume1: message:3, pattern: message:pool
consume2: message:3
consume1: message:4, pattern: message:pool
consume2: message:4
consume1: message:5, pattern: message:pool
consume2: message:5
consume1: message:6, pattern: message:pool
consume2: message:6
consume1: message:7, pattern: message:pool
consume2: message:7
consume1: message:8, pattern: message:pool
consume2: message:8
consume1: message:9, pattern: message:pool
consume2: message:9

两个监听都收到了广播消息

pom中引入redis maven 包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐