node-amqp: Having trouble with two consumers subscribing to same queue one at a time

81 views Asked by At

I have two consumers which need to process messages from same queue but only one of them at any time. A sequence of what I am trying to accomplish is like this:

  1. (start) None of the consumers have subscribed to the queue
  2. Consumer1 subscribes to queue
  3. A producer sends message to the queue, messages are delivered to consumer1
  4. Consumer1 processes messages and then unsubscribes after sometime
  5. Producer sends more messages to the queue, messages are stored in queue (autoDelete=false, so the queue is not destroyed when no consumer subscribed)
  6. Consumer2 subscribes to the queue, processes the stored messages and unsubscribes after sometime.
  7. Consumer1 subscribes, processes messages... .. so on

This works as expected initially. After step #5 above, I see that further messages from producer are delivered to both consumers , alternately to each one of them, even though only one has subscribed and the other one has unsubscribed.

The code I am using to get this working is like this:

1. Code for consumer subscribes to queue 
connection = amqp.createConnection( { url: "http://guest@localhost:5672" }
connection.on('ready', function() {
connection.queue(queuename, {autoDelete: false}, function(queue) {
      queue.bind('myexchange', '1');
      queue.subscribe(mycallback).addCallback(function(ok) { qtag = ok.consumerTag; }
}


2. code for consumer unsubcribe
queue.unsubscribe(qtag);
queue.on('basicCancelOk', function() {
}

Is there anything wrong with this code or with the overall approach towards achieving the desired sequence as I described earlier?

0

There are 0 answers