目錄
- 一、案例需求
- 二、基礎配置
- 三、代碼實現
TopicExchange與DirectExchange類似,區別在于RoutingKey
可以是多個單次的列表,并且以.
分割。
Queue與Exchange指定BindingKey
時可以使用通配符:
#
:代指0個或多個單詞。*
:代指一個單詞。
生產者源碼
消費者源碼
一、案例需求
- 在RabbitMQ控制臺中,聲明隊列
topic.queue1
和topic.queue2
。 - 在RabbitMQ控制臺中,聲明交換機
mt.topic
,將兩個隊列與其綁定。 - 在生產者服務中,利用不同的
RoutingKey
向mt.topic
交換機發送消息。 - 在消費者服務中,編寫兩個消費者,分別監聽隊列
topic.queue1
和topic.queue2
。
二、基礎配置
首先創建兩個隊列topic.queue1
和topic.queue2
。
創建一個主題交換機mt.topic,需要注意的是,在創建交換機的時候需要修改交換機的類型topic主題交換機
。
交換機創建之后,點擊交換機的名稱,綁定交換機與隊列之間的關系。
三、代碼實現
生產者
/*** 給交換機發送消息(主題交換機)* @throws InterruptedException*/
@Test
public void topicExchangeTest() throws InterruptedException {String exchangeName = "mt.topic";String message = "黃色警報 ......";
// rabbitTemplate.convertAndSend(exchangeName, "china.news", message);
// rabbitTemplate.convertAndSend(exchangeName, "japan.news", message);rabbitTemplate.convertAndSend(exchangeName, "china.weather", message);
}
消費者
@RabbitListener(queues = "topic.queue1")
public void listenTopicQueue1(String message) throws InterruptedException {System.out.println(String.format("消費者1,收到了topic.queue1: %s", message));
}@RabbitListener(queues = "topic.queue2")
public void listenTopicQueue2(String message) throws InterruptedException {System.err.println(String.format("消費者2,收到了topic.queue2: %s", message));
}