Only consuming messages with certain headers using RabbitMQ and SpringAMQP

淺唱寂寞╮ 提交于 2019-12-24 03:46:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!