TopicExchange與DirectExchange類似,差別在于routingKey必須是多個單詞的清單,并且以 . 分割。
Queue與Exchange指定BindingKey時可以使用通配符:
#:代指0個或多個單詞
*:代指一個單詞

- 在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);
}