SpringAMQP 发布订阅-TopicExchange

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

TopicExchange的使用

实现思路如下:

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

 

在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);
    }
原文地址:https://www.cnblogs.com/WarBlog/p/15479282.html