rkstar
rkstar

Reputation: 1220

current queue size in rabbitmq

i'm using amqp.node and i'd like to set up a system that will retrieve 1 message from a queue each second regardless of how many are in the queue. i want to check the queue size before i get from the channel though. how do i do that?

consumer.js

#!/usr/bin/env node

var amqp = require('amqplib/callback_api')
amqp.connect('<my_rabbitmq_host_info>', function(err, conn){
  conn.createChannel(function(err, ch){
    var q = 'message-queue'
    ch.assertQueue(q, {durable: false}, function(err, queue){
      console.log(' [*] waiting for messages in queue: %s -- to exit press ctrl+c', q)

      setInterval(function(){
       getMessage(ch, q, queue)
      }, 1000)
    })
  })
})

function getMessage(ch, q, queue){
  if( !queue ){
    return
  }

  console.log('queue %s has %d messages in it...', q, queue.messageCount)
  if( queue.messageCount > 0 ){
    console.log('getting 1 message from queue')
    ch.get(q, {noAck: false}, function(err, msg){
      console.log(' [x] message recieved: %s \n\n', msg.content.toString())
      ch.ack(msg)
    })
  }
}

i'm getting the same number for queue.messageCount each time i assume because i'm sending the same queue instance to the function each time. how do i get the current queue.messageCount ?

Upvotes: 0

Views: 1955

Answers (1)

Derick Bailey
Derick Bailey

Reputation: 72868

you have to make another call to assertQueue every time you want to get the current size. invert your code so that you call this every interval timeout, instead of only once.


setInterval(function(){

  ch.assertQueue(q, {durable: false}, function(err, queue){
    console.log(' [*] waiting for messages in queue: %s -- to exit press ctrl+c', q)
    getMessage(ch, q, queue)
  });

}, 1000)

also - this seems like a bad idea to me. i would suggest a different approach. set the prefetch limit to 1 for the consumer. then your code will only pull one message at a time.

also, this might help: http://dougbarth.github.io/2011/06/10/keeping-the-rabbit-on-a-leash.html - different language, but the concepts should translate to node

Upvotes: 2

Related Questions