问题
I'm trying to publish a message to a queue and then have certain consumers consume it only if it contains a certain header and another consumer consume it if it contains another header.
What I've done so far is to setup a headers-exchange that routes messages to a certain queue only if it contains that header.
This is the config I'm using to setup the exchange and the queue and the listener:
<!-- Register Queue Listener Beans -->
<bean id="ActionMessageListener" class="com.mycee.Action" />
<!-- Register RabbitMQ Connections -->
<rabbit:connection-factory
id="connectionFactory"
port="${rabbit.port}"
virtual-host="${rabbit.virtual}"
host="${rabbit.host}"
username="${rabbit.username}"
password="${rabbit.password}"
connection-factory="nativeConnectionFactory" />
<!-- Register RabbitMQ Listeners -->
<rabbit:listener-container
connection-factory="connectionFactory"
channel-transacted="true"
requeue-rejected="true"
concurrency="${rabbit.consumers}">
<rabbit:listener queues="${queue.myqueue}" ref="ActionMessageListener" method="handle"/>
</rabbit:listener-container>
<!-- Setup RabbitMQ headers exchange -->
<rabbit:headers-exchange id="${exchange.myexchange}" name="${exchange.myexchange}">
<rabbit:bindings>
<rabbit:binding queue="${queue.myqueue}" key="action" value="action3" />
</rabbit:bindings>
</rabbit:headers-exchange>
<rabbit:admin connection-factory="connectionFactory"/>
<rabbit:queue name="${queue.myqueue}" />
So I'm binding myqueue to myexchange using key of action and value of action3.
Now when I publish on the exchange:
the ChannelAwareMessageListener is consuming it even though the action was set to action1 instead of action3
public class Action implements ChannelAwareMessageListener {
@Override
public void onMessage(Message message, Channel channel) throws Exception {
System.out.println(message.toString());
}
}
Either I'm not using a headers-exchange correctly or I'm not configuring it correctly - any advice ?
回答1:
It doesn't work that way; you need a separate queue for each consumer. See the tutorial.
When multiple consumers consume from the same queue they compete for all messages; you can't select messages on the consumer side; the "selection" is done by the exchange by routing messages to specific queue(s).
来源:https://stackoverflow.com/questions/25489301/only-consuming-messages-with-certain-headers-using-rabbitmq-and-springamqp