Rabbit Queue
,---. | | o| ,---.
|---',---.|---.|---..|--- | |. .,---.. .,---.
| \ ,---|| || ||| | || ||---'| ||---'
` ``---^`---'`---'``---' `---\`---'`---'`---'`---'
About
This module is based on WRabbit
and Jackrabbit.
It makes RabbitMQ management and integration easy. Provides an abstraction layer
above amqplib.
It is written in typescript and requires node v10.0.0 or higher.
Most features will work with nodejs v6.0.0 and higher but using older versions than v10.0.0 is not recommended. RPC streams will not work in older versions.
By default it works well with jsons. Override properties.contentType to work with strings or binary data.
Connecting to RabbitMQ
const { Rabbit } = require('rabbit-queue');
const rabbit = new Rabbit(process.env.RABBIT_URL || 'amqp://localhost', {
prefetch: 1,
replyPattern: true,
scheduledPublish: false,
prefix: '',
socketOptions: {}
});
rabbit.on('connected', () => {
});
rabbit.on('disconnected', (err = new Error('Rabbitmq Disconnected')) => {
console.error(err);
setTimeout(() => rabbit.reconnect(), 100);
});
Usage
const { Rabbit } = require('rabbit-queue');
const rabbit = new Rabbit(process.env.RABBIT_URL || 'amqp://localhost', { scheduledPublish: true });
rabbit
.createQueue('queueName', { durable: false }, (msg, ack) => {
console.log(msg.content.toString());
ack(null, 'response');
})
.then(() => console.log('queue created'));
rabbit.publish('queueName', { test: 'data' }, { correlationId: '1' }).then(() => console.log('message published'));
rabbit
.publishWithDelay('queueName', { test: 'data' }, { correlationId: '1', expiration: '10000' })
.then(() => console.log('message will be published'));
rabbit
.getReply('queueName', { test: 'data' }, { correlationId: '1' })
.then(reply => console.log('received reply', reply));
rabbit
.getReply('queueName', { test: 'data' }, { correlationId: '1' }, '', 100)
.then(reply => console.log('received reply', reply))
.catch(error => console.log('Timed out after 100ms'));
rabbit.bindToTopic('queueName', 'routingKey');
rabbit
.getTopicReply('routingKey', { test: 'data' }, { correlationId: '1' }, '', 100)
.then(reply => console.log('received reply', reply))
.catch(error => console.log('Timed out after 100ms'));
Binding to topics
const { Rabbit } = require('rabbit-queue');
const rabbit = new Rabbit('amqp://localhost');
rabbit
.createQueue('queueName', { durable: false }, (msg, ack) => {
console.log(msg.content.toString());
ack(null, 'response');
})
.then(() => console.log('queue created'));
rabbit.bindToExchange('queueName', 'amq.topic', 'routingKey');
rabbit
.publishExchange('amq.topic', 'routingKey', { test: 'data' }, { correlationId: '1' })
.then(() => console.log('message published'));
Advanced Usage with BaseQueueHandler (will add to dlq after 3 failed retries)
const rabbit = new Rabbit('amqp://localhost');
class DemoHandler extends BaseQueueHandler {
handle({ msg, event, correlationId, startTime }) {
console.log('Received: ', event);
console.log('With correlation id: ' + correlationId);
}
afterDlq({ msg, event }) {
}
}
new DemoHandler('demoQueue', rabbit, {
retries: 3,
retryDelay: 1000,
logEnabled: true,
scope: 'SINGLETON',
createAndSubscribeToQueue: true
});
rabbit.publish('demoQueue', { test: 'data' }, { correlationId: '4' });
Get reply pattern implemented with a QueueHandler
const rabbit = new Rabbit(process.env.RABBIT_URL || 'amqp://localhost');
class DemoHandler extends BaseQueueHandler {
handle({ msg, event, correlationId, startTime }) {
console.log('Received: ', event);
console.log('With correlation id: ' + correlationId);
return Promise.resolve('reply');
}
afterDlq({ msg, event }) {
}
}
new DemoHandler('demoQueue', rabbit, {
retries: 3,
retryDelay: 1000,
logEnabled: true,
scope: 'SINGLETON'
});
rabbit
.getReply('demoQueue', { test: 'data' }, { correlationId: '5' })
.then(reply => console.log('received reply', reply));
Example where handle throws an error
const rabbit = new Rabbit(process.env.RABBIT_URL || 'amqp://localhost');
class DemoHandler extends BaseQueueHandler {
handle({msg, event, correlationId, startTime}) {
return Promise.reject(new Error('test Error'));
}
afterDlq({msg, event}) {
console.log('added to dlq');
}
}
new DemoHandler('demoQueue', rabbit,
{
retries: 3,
retryDelay: 1,
logEnabled: true
});
rabbit.getReply('demoQueue', { test: 'data' }, { correlationId: '5' })
.then(reply => console.log('received reply', reply));
.catch(error => console.log('error', error));
Example with Stream rpc (works if both consumer and producer use rabbit-queue)
const rabbit = new Rabbit(process.env.RABBIT_URL || 'amqp://localhost');
class DemoHandler extends BaseQueueHandler {
handle({ msg, event, correlationId, startTime }) {
const stream = new Readable({ read() {} });
stream.push('streaming');
stream.push('events');
stream.push(null);
return stream;
}
}
new DemoHandler('demoQueue', rabbit, {
retries: 3,
retryDelay: 1,
logEnabled: true
});
const reply = await rabbit.getReply('demoQueue', { test: 'data' }, { correlationId: '5' });
for await (const chunk of reply) {
console.log(`Received chunk: ${chunk.toString()}`);
}
Logging
Rabbit-queue uses log4js-api so you need to install log4js for logging to work.
Creations of queues, bindings are logged in debug level.
Message enqueues, dequeues are logged in info level.
Errors in BaseQueueHandler are logged in error level. (You can add your own error logging logic in afterDlq method.)
Using log4js v2 and custom appenders like log4js_honeybadger_appender you can directly log rabbit-queue errors directly to honeybadger.
log4js configuration example
log4js.configure({
appenders: {
out: { type: 'stdout', layout: { type: 'basic' } }
},
honeybadger: { type: 'log4js_honeybadger_appender' },
categories: {
default: { appenders: ['out'], level: 'info' },
'rabbit-queue': { appenders: ['out', 'honeybadger'], level: 'debug' }
}
});
Changelog
v4.2.x to > v4.4.x
RPC stream enhancement: When backpressure is enabled, the consumer can stop communication, when data received is sufficient
eg:
const reply = await rabbit.getReply('demoQueue', { test: 'data' }, { headers: { test: 1, backpressure: true }, correlationId: '1' });
for await (const chunk of reply) {
console.log(`Received chunk: ${chunk.toString()}`);
if ("sufficient_data_received") {
reply.emit(Queue.STOP_STREAM);
}
}
v4.x.x to > v4.2.x
Get reply as a stream supports two more optional headers inside properties:
backpressure (by default false),
timeout
eg:
await rabbit.getReply(
'demoQueue',
{ test: 'data' },
{ correlationId: '5', headers: { backpressure: true, timeout: 10000 } }
);
If used the rpc that responds to this request will stop sending messages until the receiving stream has consumed those messages or has buffered them (By default nodejs stream buffer for json streams is 16 objects). If this does not happen within the timeout the process will stop.
Use this feature only if both requesting and receiving part have rabbit-queue > 4.2.0
v3.x.x to v4.x.x
Code was reorganized.
RPC stream was introduced. Drops support for node older than v10.0.0 due to the usage of async generators
Supports contentType. By default it is application/json for backwards compatibility.
v2.x.x to v3.x.x
Log4js was removed. You can no longer pass your own logger in Rabbit constructor. Instead log4js-api is used and your log4js configuration is used by default if present. Logger name is rabbit-queue.
v1.x.x to V2.x.x
Queue subscribe 2ond param ack
was updated. Now it accepts as 1st param an error and as a second the response. Rpc calls will throw an error if the first param is defined.
Tests
The tests are set up with Docker + Docker-Compose,
so you don't need to install rabbitmq (or even node) to run them:
npm run test-docker