[英]Single RabbitMQ queue and multiple routing key
我們有一個將使用 RabbitMQ 的應用程序。 設計是為多個團隊使用具有多個路由鍵的單個交換單個隊列,他們將通過這個單個隊列進行通信。 我正在開發一個 java 應用程序,以使用分配給我的團隊的 routingKey 來監聽該隊列。
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "queue", durable = "true"),
exchange = @Exchange(value = "exchange", autoDelete = "false", type = "topic"),
key = "abc_rk"))
public void consumeMessagesFromRabbitMQ(Request request) throws InterruptedException {
System.out.println("Start:Request from RabbitMQ: " + request);
Thread.sleep(10000L);
System.out.println("End:Request from RabbitMQ: " + request);
}
假設隊列有 3 個 routingKey 消息,其中我的應用程序只想收聽abc_rk
。 但是當我運行這段代碼時,它不會過濾掉其他消息,而是不管我在“key =?”中設置了什么。 它從隊列中提取所有消息。 請注意,我無法更改設計並為每個 routingKey 使用單獨的隊列。
RabbitMQ 不是這樣工作的(它沒有消息選擇器的概念,不像 JMS)。
事實上,消費者對路由鍵一無所知,只有生產者; 您在@RabbitListener
上看到它的唯一原因是幫助配置。
為了做你想做的事,你需要使用各自的路由鍵將 3 個不同的隊列綁定到交換器。
請注意,我無法更改設計並為每個 routingKey 使用單獨的隊列。
您可以將MessagePostProcessor
添加到容器( afterReceivePostProcessors
)以通過返回 null 來丟棄不需要的消息。 這是框架為過濾消息提供的唯一機制。
/**
* Set {@link MessagePostProcessor}s that will be applied after message reception, before
* invoking the {@link MessageListener}. Often used to decompress data. Processors are invoked in order,
* depending on {@code PriorityOrder}, {@code Order} and finally unordered.
* @param afterReceivePostProcessors the post processor.
* @since 1.4.2
* @see #addAfterReceivePostProcessors(MessagePostProcessor...)
*/
public void setAfterReceivePostProcessors(MessagePostProcessor... afterReceivePostProcessors) {
但最好的解決方案是 3 個隊列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.