What is amqplib?
The amqplib npm package is a library for Node.js that provides an interface for interacting with AMQP 0-9-1 compatible message brokers, such as RabbitMQ. It allows for the sending and receiving of messages over queues and exchanges, and supports various messaging patterns.
What are amqplib's main functionalities?
Connecting to a RabbitMQ server
This code demonstrates how to connect to a RabbitMQ server using amqplib. It establishes a connection and creates a channel for sending and receiving messages.
const amqp = require('amqplib');
async function connect() {
try {
const connection = await amqp.connect('amqp://localhost');
const channel = await connection.createChannel();
console.log('Connected to RabbitMQ');
// Additional code to interact with the channel
} catch (error) {
console.error('Connection failed', error);
}
}
connect();
Sending a message to a queue
This code snippet shows how to send a message to a specific queue. It connects to the server, creates a channel, asserts the queue, sends the message, and then closes the channel and connection.
const amqp = require('amqplib');
async function sendMessage(queue, message) {
const connection = await amqp.connect('amqp://localhost');
const channel = await connection.createChannel();
await channel.assertQueue(queue, { durable: false });
channel.sendToQueue(queue, Buffer.from(message));
console.log(`Message sent: ${message}`);
await channel.close();
await connection.close();
}
sendMessage('myQueue', 'Hello World!');
Receiving messages from a queue
This example demonstrates how to receive messages from a queue. It sets up a consumer that listens for messages on the specified queue and acknowledges them after processing.
const amqp = require('amqplib');
async function receiveMessages(queue) {
const connection = await amqp.connect('amqp://localhost');
const channel = await connection.createChannel();
await channel.assertQueue(queue, { durable: false });
channel.consume(queue, (msg) => {
if (msg !== null) {
console.log(`Received message: ${msg.content.toString()}`);
channel.ack(msg);
}
});
}
receiveMessages('myQueue');
Setting up exchanges and routing
This code sets up an exchange and a queue, then binds them with a routing key. It also sets up a consumer to receive messages sent to the exchange with the specific routing key.
const amqp = require('amqplib');
async function setupExchangeAndRouting() {
const connection = await amqp.connect('amqp://localhost');
const channel = await connection.createChannel();
await channel.assertExchange('myExchange', 'direct', { durable: false });
const { queue } = await channel.assertQueue('', { exclusive: true });
channel.bindQueue(queue, 'myExchange', 'myRoutingKey');
channel.consume(queue, (msg) => {
if (msg !== null) {
console.log(`Received: ${msg.content.toString()}`);
channel.ack(msg);
}
});
}
setupExchangeAndRouting();
Other packages similar to amqplib
rabbit.js
rabbit.js is a messaging library for Node.js that is built on top of amqplib. It provides a simpler API for common messaging patterns. However, it may not be as actively maintained or feature-rich as amqplib.
rascal
rascal is an advanced message bus for Node.js that wraps amqplib. It provides additional features like configuration-based setup, automatic reconnection, and message redelivery. It's a higher-level abstraction compared to amqplib.
seneca-amqp-transport
seneca-amqp-transport is a plugin for the Seneca microservices toolkit that allows Seneca-based microservices to communicate over AMQP using RabbitMQ. It's more specialized for use with Seneca, whereas amqplib is a general-purpose AMQP library.
AMQP 0-9-1 library and client for Node.JS
npm install amqplib
A library for making AMQP 0-9-1 clients for Node.JS, and an AMQP 0-9-1
client for Node.JS v0.8, v0.9, v0.10, and v0.11.
Project status:
- Expected to work
- Complete high-level and low-level APIs (i.e., all bits of the protocol)
- A fair few tests
- Measured test coverage
- Ports of the RabbitMQ tutorials as examples
Still working on:
- Getting to 100% (or very close to 100%) test coverage
- Settling on completely stable APIs
- Establishing a long history of battle-testing in production (if
anyone has been using it in production, do let me know)
Client API example
var q = 'tasks';
var open = require('amqplib').connect('amqp://localhost');
open.then(function(conn) {
var ok = conn.createChannel();
ok = ok.then(function(ch) {
ch.assertQueue(q);
ch.sendToQueue(q, new Buffer('something to do'));
});
return ok;
}).then(null, console.warn);
open.then(function(conn) {
var ok = conn.createChannel();
ok = ok.then(function(ch) {
ch.assertQueue(q);
ch.consume(q, function(msg) {
if (msg !== null) {
console.log(msg.content.toString());
ch.ack(msg);
}
});
});
return ok;
}).then(null, console.warn);
Running tests
npm test
Best run with a locally-installed RabbitMQ, but you can point it at
another using the environment variable URL
; e.g.,
URL=amqp://dev.rabbitmq.com npm test
NB You may experience test failures due to timeouts if using the
dev.rabbitmq.com instance.
You can run it under different versions of Node.JS using nave:
nave use 0.8 npm test
or run the tests on all supported versions of Node.JS in one go:
make test-all-nodejs
(which also needs nave
installed, of course).
Lastly, setting the environment variable LOG_ERRORS
will cause the
tests to output error messages encountered, to the console; this is
really only useful for checking the kind and formatting of the errors.
LOG_ERRORS=true npm test
Test coverage
make coverage
open file://`pwd`/coverage/lcov-report/index.html