Search code examples
phproutesrabbitmqconsumerpublisher

rabbitmq consumer getting messages of different routing key


We have two consumers with c1 (in php) binding to exchange 1, queue 1 and routing key 1; and c2 (in java) binging to exchange 1, queue 1 and routing key 2. i.e. only routing keys are different, but exchange and queue are same.

in php, we do binding as the following does

$channel->queue_bind($this->queue, $this->exchange, $this->routing1);

in java, the following

channel.queueBind(queue, exchange, routing2);

Now when we publish messages meant for c2 using routing key 2, we observed that the messages got received by c1 and c2 in round robin fashion instead of only got received by c2.

The senders for c1 and c2 are all in php, with sender for c1 does the following

$channel->basic_publish($message, $this->exchange, $this->routing1);

And sender for c2 does the following

$channel->basic_publish($message, $this->exchange, $this->routing2);

Do we have correct assumption? Is there anything wrong with the code?

[Edit1] as experiment, we changed to bind to separate queues for the two consumers and the publishers. and we observed that the messages meant for c2 (q2 and r2) got received by both c2 and c1... something is wrong here.


Solution

  • only routing keys are different, but exchange and queue are same.

    you have designed your queues and consumers to produce this behavior.

    when RMQ has multiple consumers for a queue, it will round-robin the messages from that queue, to all available consumers. this is by design in RMQ - it allows you to scale out the number of consumers for a given queue, so you can handle larger volumes of messages.

    if you need C1 and C2 to receive different messages, and not round-robin messages from Q1 between them, then C1 and C2 must have different queues to which they are subscribed.

    for example:

    • E1 with routing key 1 should go to QC1
    • E1 with routing key 2 should go to QC2
    • C1 should consume messages from QC1
    • C2 should consume messages from QC2

    by having separate queues for the consumers, you will guarantee messages going to the proper consumer