RedisSMQ

A simple high-performance Redis message queue for Node.js.

README

RedisSMQ

A simple high-performance Redis message queue for Node.js.


RedisSMQ


Tests Code quality Coverage Status NPM version NPM downloads


RedisSMQ is a Node.js library for queuing messages (aka jobs) and processing them asynchronously with consumers. Backed by Redis, it allows scaling up your application with ease of use.

Features


Multi-Queue Producers & Multi-Queue Consumers: Offering flexible Producer/Consumer models, with focus on simplicity and without tons of features. This can make RedisSMQ an ideal message broker for your microservices.
at-least-once/at-most-once Delivery: In case of failures, while delivering or processing a message, RedisSMQ can guaranty that the message will be not lost and redelivered again. When configured to do so, RedisSMQ can also ensure that the message is delivered at-most-once.
Different Exchange Types: RedisSMQ offers 3 types of exchanges: Direct Exchange, Topic Exchange, and Fanout Exchange for publishing a message to one or multiple queues.
Message Expiration: A message will not be delivered if it has been in a queue for longer than a given amount of time, called TTL (time-to-live).
Message Consumption Timeout: Timeout for consuming messages.
Queue Rate Limiting: Allowing you to control the rate at which the messages are consumed from a given queue.
Scheduling Messages: Messages can be configured to be delayed, delivered for N times with an optional period between deliveries, and to be scheduled using CRON expressions.
Reliable Priority Queues: Supports priority messaging.
Multiplexing: A feature which allows message handlers to use a single redis connection to dequeue and consume messages.  
HTTP API: an HTTP interface is provided to interact with the MQ.
Web UI: RedisSMQ can be managed also from your web browser.
Logging: RedisSMQ comes with a built-in JSON logger, but can also use your application logger.
Configurable: Many options and features can be configured.
Multiple Redis clients: Depending on your preferences, RedisSMQ can use either node-redis v3, node-redis v4, or ioredis.
Highly optimized: Strongly-typed and implemented using pure callbacks, with small memory footprint and no memory leaks. See Callback vs Promise vs Async/Await benchmarks.


RedisSMQ Use Case: Multi-Queue Producers & Multi-Queue Consumers


 

RedisSMQ Overview

Table of Content


   1. Basics
       1. Message
       2. Producer
       3. Consumer
          1. Message Acknowledgement
      1. Scheduling Messages
      2. Message Exchanges
      3. Queue Rate Limiting
      4. Multiplexing
      5. Message Manager
      6. Queue Manager
      7. HTTP API
      8. Web UI
      9. Logs

What's new?


2022.10.06

:rocket: RedisSMQ v7.1 is out! This new release extends the message queue features by introducing Message Exchanges.
Also, the Web UI has been reworked for better user experience and
to fully support message exchanges and other various routine operations.

Installation


  1. ```text
  2. npm install redis-smq-common redis-smq --save
  3. ```

Considerations:

- Minimal Node.js version is >= 14 (RedisSMQ is tested under current active LTS and maintenance LTS Node.js releases).
- Minimal Redis server version is 2.6.12 (RedisSMQ is tested under Redis v2.6, v3, v4, v5, and v6).

Configuration


See Configuration for more details.

Usage


Basics


RedisSMQ provides 3 classes in order to work with the message queue: Message, Producer, and Consumer.

Producers and consumers exchange data using one or multiple queues that may be created using the QueueManager.

A queue is responsible for holding messages which are produced by producers and are delivered to consumers.

RedisSMQ supports 2 types of queues: LIFO Queues and Priority Queues.

  1. ``` js
  2. const { QueueManager } = require('redis-smq');
  3. const config = require('./config')

  4. QueueManager.createInstance(config, (err, queueManager) => {
  5.   if (err) console.log(err);
  6.   // Creating a LIFO queue
  7.   else queueManager.queue.create('test_queue', false, (err) => console.log(err));
  8. })
  9. ```

See Queues for more details.

Message


Message class is responsible for creating messages that may be published.

A message can carry your application data, sometimes referred to as message payload, which may be delivered to a consumer to be processed asynchronously.  

The message payload can be of any valid JSON data type. It may be a simple text message like Hello world or a complex data type like {hello: 'world'}.

  1. ``` js
  2. const { Message } = require('redis-smq');
  3. const message = new Message();
  4. message
  5.     .setBody({hello: 'world'})
  6.     .setTTL(3600000)
  7.     .setRetryThreshold(5);
  8. ```

The Message class provides many methods for setting up different message parameters such as message body, message priority, message TTL, etc.

See Message Reference for more details.

Producer


A Producer instance allows to publish a message to a queue.

You can use a single Producer instance to produce messages, including messages with priority, to one or multiple queues.

Before publishing a message do not forget to set an exchange for the message using setQueue(), setTopic(), or setFanOut(). Otherwise, an error will be returned. See Message Exchanges for more details.

  1. ``` js
  2. 'use strict';
  3. const {Message, Producer} = require('redis-smq');

  4. const producer = new Producer();
  5. producer.run((err) => {
  6.    if (err) throw err;
  7.    const message = new Message();
  8.    message
  9.            .setBody({hello: 'world'})
  10.            .setTTL(3600000) // message expiration (in millis)
  11.            .setQueue('test_queue'); // setting up a direct exchange
  12.    message.getId() // null
  13.    producer.produce(message, (err) => {
  14.       if (err) console.log(err);
  15.       else {
  16.          const msgId = message.getId(); // string
  17.          console.log('Successfully produced. Message ID is ', msgId);
  18.       }
  19.    });
  20. })
  21. ```

Starting with v7.0.6, before producing messages you need first to run your producer instance.

See Producer Reference for more details.

Consumer


A Consumer instance can be used to receive and consume messages from one or multiple queues.

To consume messages from a queue, the Consumer class provides the consume() method which allows to register amessage handler.

A message handler is a function that receives a delivered message from a given queue.

Message handlers can be registered at any time, before or after a consumer has been started.

In contrast to producers, consumers are not automatically started upon creation. To start a consumer use the run() method.

To stop consuming messages from a queue and to remove the associated message handler from your consumer, use the cancel() method.

To shut down completely your consumer and tear down all message handlers, use the shutdown() method.

  1. ``` js
  2. 'use strict';

  3. const { Consumer } = require('redis-smq');

  4. const consumer = new Consumer();

  5. const messageHandler = (msg, cb) => {
  6.    const payload = msg.getBody();
  7.    console.log('Message payload', payload);
  8.    cb(); // acknowledging the message
  9. };

  10. consumer.consume('test_queue', messageHandler, (err) => {
  11.    if (err) console.error(err);
  12. });

  13. consumer.run();
  14. ```

Message Acknowledgement

Once a message is received, to acknowledge it, you invoke the callback function without arguments, as shown in the example above.

Message acknowledgment informs the MQ that the delivered message has been successfully consumed.

If an error occurred while processing a message, you can unacknowledge it by passing in the error to the callback function.

By default, unacknowledged messages are re-queued and delivered again unless message retry threshold is exceeded.

Delivered messages that couldn't be processed or can not be delivered to consumers are moved to a system generated queue called dead-letter queue (DLQ).

By default, RedisSMQ does not store acknowledged and dead-lettered messages for saving disk and memory spaces, and also to increase message processing performance.

If you need such feature, you can enable it from your configuration object.

See Consumer Reference for more details.

Advanced Topics





  





RedisSMQ Architecture



Performance


See Performance for more details.

Contributing


So you are interested in contributing to this project? Please see CONTRIBUTING.md.

License