SpringAMQP 发布订阅-TopicExchange

发布时间:2022-07-01 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了SpringAMQP 发布订阅-TopicExchange脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

TopicExchange与DirectExchange类似,区别在于routingKey必须是多个单词的列表,并且以 . 分割。Queue与Exchange指定BindingKey时可以使用通配符:#:代指0个或多个单词*:代指一个单词

SpringAMQP 发布订阅-TopicExchange

 

TopicExchange的使用

实现思路如下:

  • 在consumer服务中,编写两个消费者方法,分别监听topic.queue1和topic.queue2
    • 利用@RabbITListener声明Exchange、Queue、BindingKey
  • 在Publisher中编写测试方法
    • 向指定的Exchange和RoutingKey发送消息

 

SpringAMQP 发布订阅-TopicExchange

在consumer服务中,编写两个消费者方法

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("topic.queue1"),
            exchange = @Exchange(name = "marw.topic", tyPE = ExchangeTypes.TOPIC),
            key = "#.news"
    ))
    public void listenTopicQueue1(String msg) throws InterruptedException {
        System.out.PRintln("listenTopicQueue1 消费者接收到天气消息 :【" + msg + "】");
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("topic.queue2"),
            exchange = @Exchange(name = "marw.topic", type = ExchangeTypes.TOPIC),
            key = "china.#"
    ))
    public void listenTopicQueue2(String msg) throws InterruptedException {
        System.err.println("listenTopicQueue2 消费者接收到中国消息 :【" + msg + "】");
    }

publisher中编写测试方法

    @test
    public void testTopicQueue() throws InterruptedException {
        String queueName = "marw.topic";
        String message = "今天天气不错";
        rabbitTemplate.convertAndSend(queueName, "china.news", message);
    }

 

脚本宝典总结

以上是脚本宝典为你收集整理的SpringAMQP 发布订阅-TopicExchange全部内容,希望文章能够帮你解决SpringAMQP 发布订阅-TopicExchange所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。