Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kururu-abdo/0ea69faa65ccf4a4a987e6606e1082e9 to your computer and use it in GitHub Desktop.
Save kururu-abdo/0ea69faa65ccf4a4a987e6606e1082e9 to your computer and use it in GitHub Desktop.
Example of reading from RabbitMQ in Node.js

RabbitMQ with Node.js

Install and run RabbitMQ server

Download image

docker pull rabbitmq:management

Run server with web management

docker run -d -p 15672:15672 -p 5672:5672 -e RABBITMQ_NODENAME=my-rabbit --name some-rabbit rabbitmq:management

MORE INFO: https://registry.hub.docker.com/_/rabbitmq/

Node.js client

Reading from existing queue

var amqp = require('amqp');
 
var connection = amqp.createConnection({ host: 'localhost', port: 5672 });

connection.on('ready', function () {
  connection.queue('queueName', {autoDelete: false, passive: true}, function (q) {
    q.bind('#');
    q.subscribe({ ack: true }, function (message) {
      console.log(message.data.toString('utf8'));
      q.shift();
    });
  });
});

Fill queue with some dummy items

var amqp = require('amqp');
 
var connection = amqp.createConnection({ host: 'localhost', port: 5672 });

var started = false;

connection.on('ready', function () {
    if (started === false) {
        started = true;
        connection.exchange('', {confirm: true}, function (exchange) {
            publish(exchange, 1);
        });
    }
});

function publish(exc, i) {
    if (i === 100) {
        return connection.disconnect();
    }
    
    exc.publish('queueName', i, {}, function (err) {
    console.log('Added ' + i);
    setTimeout(function() {
        publish(exc, ++i);
    }, 1);
    });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment