1、簡介
????????在Fanout模式中,一條消息,會被所有訂閱的隊列都消費。但是,在某些場景下,我們希望不同的消息被不同的隊列消費。這時就要用到Direct類型的Exchange。
?
?2、特點
在Direct模型下:
隊列與交換機的綁定,不能是任意綁定了,而是要指定一個
RoutingKey
(路由key)消息的發(fā)送方在 向 Exchange發(fā)送消息時,也必須指定消息的
RoutingKey
。Exchange不再把消息交給每一個綁定的隊列,而是根據(jù)消息的
Routing Key
進行判斷,只有隊列的Routingkey
與消息的Routing key
完全一致,才會接收到消息
?3、設置隊列
4、設置交換機
5、綁定隊列
?6、設置生產(chǎn)者
@Test
void testSendDirect1() {
String exchangeName = "test.direct";
String msg = "紅色通知";
rabbitTemplate.convertAndSend(exchangeName, "red", msg);
}
@Test
void testSendDirect2() {
String exchangeName = "test.direct";
String msg = "藍色通知";
rabbitTemplate.convertAndSend(exchangeName, "blue", msg);
}
@Test
void testSendDirect3() {
String exchangeName = "test.direct";
String msg = "黃色通知";
rabbitTemplate.convertAndSend(exchangeName, "yellow", msg);
}
7、設置消費者
@RabbitListener(queues = "direct.queue1")
public void listenDirectQueue1(String msg) {
System.out.println("消費者1接收到direct.queue1的消息:【" + msg + "】");
}
@RabbitListener(queues = "direct.queue2")
public void listenDirectQueue2(String msg) {
System.out.println("消費者2接收到direct.queue2的消息:【" + msg + "】");
}
8、測試
9、總結(jié)
Direct交換機與Fanout交換機的差異?
Fanout交換機將消息路由給每一個與之綁定的隊列
Direct交換機根據(jù)RoutingKey判斷路由給哪個隊列文章來源:http://www.zghlxwxcb.cn/news/detail-824297.html
如果多個隊列具有相同的RoutingKey,則與Fanout功能類似文章來源地址http://www.zghlxwxcb.cn/news/detail-824297.html
到了這里,關于rabbitmq基礎-java-4、Direct交換機的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!