概述

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

利用SpringAMQP演示TopicExchange的使用

实现思路如下:

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

绑定关系

//交给spring管理
@Component
public class SpringRabbitListener {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "topic.queue1"),
            exchange = @Exchange(name = "topic.exchange", type = ExchangeTypes.TOPIC),
            key = "china.#"
    ))
    public void listenTopicFanout1(String msg) {
        System.out.println("【topic.queue1】:" + msg);

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "topic.queue2"),
            exchange = @Exchange(name = "topic.exchange", type = ExchangeTypes.TOPIC),
            key = "#.news"
    ))
    public void listenTopicFanout2(String msg) {
        System.out.println("【topic.queue2】:" + msg);
    }
}

测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAmqpTest {
    @Autowired
    private RabbitTemplate template;

    @Test
    public void testSendTopicExchange() {
        String exchangeName = "topic.exchange";
        String message = "消息来啦!!!";
        template.convertAndSend(exchangeName, "china.news", message);
    }
}

image-1655738283230


@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAmqpTest {
    @Autowired
    private RabbitTemplate template;

    @Test
    public void testSendTopicExchange() {
        String exchangeName = "topic.exchange";
        String message = "消息来啦!!!";
        template.convertAndSend(exchangeName, "china.weather", message);
    }
}

image-1655738705218


@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAmqpTest {
    @Autowired
    private RabbitTemplate template;

    @Test
    public void testSendTopicExchange() {
        String exchangeName = "topic.exchange";
        String message = "消息来啦!!!";
        template.convertAndSend(exchangeName, "usa.news", message);
    }
}

image-1655738813324

总结

描述下Direct交换机与Topic交换机的差异?

  • Topic交换机接收的消息RoutingKey必须是多个单词,以 . 分割
  • Topic交换机与队列绑定时的bindingKey可以指定通配符
  • #:代表0个或多个词
  • *:代表1个词