jwalton / node-amqp-connection-manager

Auto-reconnect and round robin support for amqplib.
527 stars 104 forks source link

amqp-connection-manager

NPM version Build Status semantic-release

Connection management for amqplib. This is a wrapper around amqplib which provides automatic reconnects.

Features

Installation

npm install --save amqplib amqp-connection-manager

Basics

The basic idea here is that, usually, when you create a new channel, you do some setup work at the beginning (like asserting that various queues or exchanges exist, or binding to queues), and then you send and receive messages and you never touch that stuff again.

amqp-connection-manager will reconnect to a new broker whenever the broker it is currently connected to dies. When you ask amqp-connection-manager for a channel, you specify one or more setup functions to run; the setup functions will be run every time amqp-connection-manager reconnects, to make sure your channel and broker are in a sane state.

Before we get into an example, note this example is written using Promises, however much like amqplib, any function which returns a Promise will also accept a callback as an optional parameter.

Here's the example:

var amqp = require('amqp-connection-manager');

// Create a new connection manager
var connection = amqp.connect(['amqp://localhost']);

// Ask the connection manager for a ChannelWrapper.  Specify a setup function to
// run every time we reconnect to the broker.
var channelWrapper = connection.createChannel({
  json: true,
  setup: function (channel) {
    // `channel` here is a regular amqplib `ConfirmChannel`.
    // Note that `this` here is the channelWrapper instance.
    return channel.assertQueue('rxQueueName', { durable: true });
  },
});

// Send some messages to the queue.  If we're not currently connected, these will be queued up in memory
// until we connect.  Note that `sendToQueue()` and `publish()` return a Promise which is fulfilled or rejected
// when the message is actually sent (or not sent.)
channelWrapper
  .sendToQueue('rxQueueName', { hello: 'world' })
  .then(function () {
    return console.log('Message was sent!  Hooray!');
  })
  .catch(function (err) {
    return console.log('Message was rejected...  Boo!');
  });

Sometimes it's handy to modify a channel at run time. For example, suppose you have a channel that's listening to one kind of message, and you decide you now also want to listen to some other kind of message. This can be done by adding a new setup function to an existing ChannelWrapper:

channelWrapper.addSetup(function (channel) {
  return Promise.all([
    channel.assertQueue('my-queue', { exclusive: true, autoDelete: true }),
    channel.bindQueue('my-queue', 'my-exchange', 'create'),
    channel.consume('my-queue', handleMessage),
  ]);
});

addSetup() returns a Promise which resolves when the setup function is finished (or immediately, if the underlying connection is not currently connected to a broker.) There is also a removeSetup(setup, teardown) which will run teardown(channel) if the channel is currently connected to a broker (and will not run teardown at all otherwise.) Note that setup and teardown must either accept a callback or return a Promise.

See a complete example in the examples folder.

API

connect(urls, options)

Creates a new AmqpConnectionManager, which will connect to one of the URLs provided in urls. If a broker is unreachable or dies, then AmqpConnectionManager will try the next available broker, round-robin.

Options:

AmqpConnectionManager events

AmqpConnectionManager#createChannel(options)

Create a new ChannelWrapper. This is a proxy for the actual channel (which may or may not exist at any moment, depending on whether or not we are currently connected.)

Options:

AmqpConnectionManager#isConnected()

Returns true if the AmqpConnectionManager is connected to a broker, false otherwise.

AmqpConnectionManager#close()

Close this AmqpConnectionManager and free all associated resources.

ChannelWrapper events

ChannelWrapper#addSetup(setup)

Adds a new 'setup handler'.

setup(channel, [cb]) is a function to call when a new underlying channel is created - handy for asserting exchanges and queues exists, and whatnot. The channel object here is a ConfirmChannel from amqplib. The setup function should return a Promise (or optionally take a callback) - no messages will be sent until this Promise resolves.

If there is a connection, setup() will be run immediately, and the addSetup Promise/callback won't resolve until setup is complete. Note that in this case, if the setup throws an error, no 'error' event will be emitted, since you can just handle the error here (although the setup will still be added for future reconnects, even if it throws an error.)

Setup functions should, ideally, not throw errors, but if they do then the ChannelWrapper will emit an 'error' event.

ChannelWrapper#removeSetup(setup, teardown)

Removes a setup handler. If the channel is currently connected, will call teardown(channel), passing in the underlying amqplib ConfirmChannel. teardown should either take a callback or return a Promise.

ChannelWrapper#publish and ChannelWrapper#sendToQueue

These work exactly like their counterparts in amqplib's Channel, except that they return a Promise (or accept a callback) which resolves when the message is confirmed to have been delivered to the broker. The promise rejects if either the broker refuses the message, or if close() is called on the ChannelWrapper before the message can be delivered.

Both of these functions take an additional option when passing options:

ChannelWrapper#ack and ChannelWrapper#nack

These are just aliases for calling ack() and nack() on the underlying channel. They do nothing if the underlying channel is not connected.

ChannelWrapper#queueLength()

Returns a count of messages currently waiting to be sent to the underlying channel.

ChannelWrapper#close()

Close a channel, clean up resources associated with it.