Reputation: 45
I have a requirement where i have to listen to same exchange,same queue but different routes.
below is the code for listening messages from diff routes
@Component
public class EmailMessageHandler {
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "queue", durable = "true"),
exchange = @Exchange(value = "exchange", durable = "true" ,type = ExchangeTypes.DIRECT),
key = "key1")
)
public void method1(String message) throws Exception {
System.out.println("New message received" + message);
}
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "queue", durable = "true"),
exchange = @Exchange(value ="exchange", durable = "true",type = ExchangeTypes.DIRECT),
key = "key2")
)
public void method(Message message) throws Exception {
System.out.println("New message received" + message);
}
}
The problem here is the messages are not going to the right method consistently, eg: the key1 message is going to key2 and viceversa. Let me know if anybody needs additional details.Appreciate your help in advance
Upvotes: 3
Views: 871
Reputation: 13235
I do not think that your goal is possible with RabbitMQ. It goes against AMQP protocol.
I have to listen to same exchange,same queue but different routes.
Route is not AMQP concept. AMQP has concept of binding- defining how messages are moved from from exchange (where they are published to) to queue/queues (where they are consumed from).
You should use different queues for different routes (consumers). Each (unique) consumer should consume from different queue. There will be no chance of inconsistent routing. Two consumers consuming from same queue should be used for load balancing only. For routing you may use direct exchange (simplest, best for given case) or header exchange.
See https://www.rabbitmq.com/tutorials/amqp-concepts.html
In your sample, you have bound two routing keys to the same queue. So, any message send to exchange will be delivered to that queue. Then, you have two consumers for that queue. So indeed, random consumer will be invoked for each message (load-balancing between consumers).
You may check that in RabbitMQ GUI. You will see two consumers connected to the same queue.
Upvotes: 2