Spring Boot整合Redis实现消息队列的发布订阅

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

加入Redis的集成依赖,springboot会帮我们自动注入StringRedisTemplate操作模板


            org.springframework.boot
            spring-boot-starter-data-redis
        

发布消息,通过StringRedisTemplate将消息发布到mytopic主题上

@RestController
@RequestMapping("redis")
public class RedisPublish {
    private int m = 0;
    @Autowired
    private StringRedisTemplate template;
    @RequestMapping("publish")
    public String publish(){
        int index = m;
        for(int i=m;i 
   

订阅消息

需要配置一个消息监听者容器,容器需要连接工厂以及消息监听器,在消息监听器中需要配置消息处理对象以及处理的方法

@Configuration
public class MyRedisConf {
    
​
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                                   MessageListenerAdapter listenerAdapter){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter,new PatternTopic("mytopic"));
        return container;
    }
​
    /**
     * 绑定消息监听者和接收监听的方法,必须要注入这个监听器,不然会报错
     */
    @Bean
    public MessageListenerAdapter listenerAdapter(){
        return new MessageListenerAdapter(new Receiver(),"receiveMessage");
    }
​
    
}
​
@Slf4j
public class Receiver {
​
    public void receiveMessage(String message) {
        log.info("Received <" + message + ">");
    }
​
}
​

启动程序,通过http://localhost:8081/redis/publish发布消息

控制台显示如下

2018-05-17 11:18:55,258 - Received <这是我发第3条的消息啊>
2018-05-17 11:18:55,259 - Received <这是我发第5条的消息啊>
2018-05-17 11:18:55,260 - Received <这是我发第0条的消息啊>
2018-05-17 11:18:55,258 - Received <这是我发第1条的消息啊>
2018-05-17 11:18:55,261 - Received <这是我发第7条的消息啊>
2018-05-17 11:18:55,259 - Received <这是我发第2条的消息啊>
2018-05-17 11:18:55,260 - Received <这是我发第4条的消息啊>
2018-05-17 11:18:55,260 - Received <这是我发第6条的消息啊>
2018-05-17 11:18:55,262 - Received <这是我发第8条的消息啊>
2018-05-17 11:18:55,269 - Received <这是我发第9条的消息啊>

 

转载于:https://my.oschina.net/watsonos/blog/2221479

你可能感兴趣的:(数据库,java,python)