Only consuming messages with certain headers using

2019-07-18 09:28发布

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.

enter image description here

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:

enter image description here

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条回答
虎瘦雄心在
2楼-- · 2019-07-18 10:22

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).

查看更多
登录 后发表回答