spring boot redis 广播消息
spring boot reids 消息广播
·
新建两个订阅监听
@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>
更多推荐
已为社区贡献1条内容
所有评论(0)