Faheel Mohammad
Faheel Mohammad

Reputation: 115

Listening for rabbitmq mesasges

I have a node server which basically publishes messages to a rabbitmq queue and another node js server which basically consumes it. What i want is to have the consumer server to listen and process the messages from the queue as soon as a new message is published from the node server. I am using ampqlib for the rabbitmq package for node js

Upvotes: 0

Views: 1317

Answers (1)

O. Jones
O. Jones

Reputation: 108641

ampqlib's documentation explains how to create a consumer for a rabbitmq queue.

Something like this might work. (not debugged).

const amqplib = require('amqplib')
const queueName = 'tasks'
const mqUrl = 'amqp://localhost'
...
async function consume(mqUrl, queueName, dispatchFunction) {
  const conn = await connect(mqUrl)
  const channel = await conn.createChannel()
  const ok = await channel.assertQueue(queueName)
  while (true) {
    try {
      const message = await channel.consume(queueName)
      if (message !== null) {
        channel.ack(message)
        dispatchFunction(null, message)
      }
    } catch (err) {
      dispatchFunction(err, null)
    }
  }
}

consume(mqUrl, queueName, 
  function (err, message) {
    if (err) return console.log(err)
    /* do something useful with the message */
  } )
.then()
.catch(function (err) {
  console.error('cannot access queue', err, mqUrl, queueName)
} )

Upvotes: 1

Related Questions