RabbitMQ

RabbitMQ is an open-source and lightweight message broker which supports multiple messaging protocols. It can be deployed in distributed and federated configurations to meet high-scale, high-availability requirements. In addition, it’s the most widely deployed message broker, used worldwide at small startups and large enterprises.

Installation

To start building RabbitMQ-based microservices, first install the required packages:

  1. $ npm i --save amqplib amqp-connection-manager

Overview

To use the RabbitMQ transporter, pass the following options object to the createMicroservice() method:

main.ts

  1. const app = await NestFactory.createMicroservice<MicroserviceOptions>(ApplicationModule, {
  2. transport: Transport.RMQ,
  3. options: {
  4. urls: ['amqp://localhost:5672'],
  5. queue: 'cats_queue',
  6. queueOptions: {
  7. durable: false
  8. },
  9. },
  10. });
  1. const app = await NestFactory.createMicroservice(ApplicationModule, {
  2. transport: Transport.RMQ,
  3. options: {
  4. urls: ['amqp://localhost:5672'],
  5. queue: 'cats_queue',
  6. queueOptions: {
  7. durable: false
  8. },
  9. },
  10. });

Hint The Transport enum is imported from the @nestjs/microservices package.

Options

The options property is specific to the chosen transporter. The RabbitMQ transporter exposes the properties described below.

urlsConnection urls
queueQueue name which your server will listen to
prefetchCountSets the prefetch count for the channel
isGlobalPrefetchCountEnables per channel prefetching
noAckIf false, manual acknowledgment mode enabled
queueOptionsAdditional queue options (read more here)
socketOptionsAdditional socket options (read more here)

Client

Like other microservice transporters, you have several options for creating a RabbitMQ ClientProxy instance.

One method for creating an instance is to use the ClientsModule. To create a client instance with the ClientsModule, import it and use the register() method to pass an options object with the same properties shown above in the createMicroservice() method, as well as a name property to be used as the injection token. Read more about ClientsModulehere.

  1. @Module({
  2. imports: [
  3. ClientsModule.register([
  4. {
  5. name: 'MATH_SERVICE',
  6. transport: Transport.RMQ,
  7. options: {
  8. urls: ['amqp://localhost:5672'],
  9. queue: 'cats_queue',
  10. queueOptions: {
  11. durable: false
  12. },
  13. },
  14. },
  15. ]),
  16. ]
  17. ...
  18. })

Other options to create a client (either ClientProxyFactory or @Client()) can be used as well. You can read about them here.

Context

In more sophisticated scenarios, you may want to access more information about the incoming request. When using the RabbitMQ transporter, you can access the RmqContext object.

  1. @MessagePattern('notifications')
  2. getNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {
  3. console.log(`Pattern: ${context.getPattern()}`);
  4. }
  1. @Bind(Payload(), Ctx())
  2. @MessagePattern('notifications')
  3. getNotifications(data, context) {
  4. console.log(`Pattern: ${context.getPattern()}`);
  5. }

Hint@Payload(), @Ctx() and RmqContext are imported from the @nestjs/microservices package.

To access the original RabbitMQ message (with the properties, fields, and content), use the getMessage() method of the RmqContext object, as follows:

  1. @MessagePattern('notifications')
  2. getNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {
  3. console.log(context.getMessage());
  4. }
  1. @Bind(Payload(), Ctx())
  2. @MessagePattern('notifications')
  3. getNotifications(data, context) {
  4. console.log(context.getMessage());
  5. }

To retrieve a reference to the RabbitMQ channel, use the getChannelRef method of the RmqContext object, as follows:

  1. @MessagePattern('notifications')
  2. getNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {
  3. console.log(context.getChannelRef());
  4. }
  1. @Bind(Payload(), Ctx())
  2. @MessagePattern('notifications')
  3. getNotifications(data, context) {
  4. console.log(context.getChannelRef());
  5. }

Message acknowledgement

To make sure a message is never lost, RabbitMQ supports message acknowledgements. An acknowledgement is sent back by the consumer to tell RabbitMQ that a particular message has been received, processed and that RabbitMQ is free to delete it. If a consumer dies (its channel is closed, connection is closed, or TCP connection is lost) without sending an ack, RabbitMQ will understand that a message wasn’t processed fully and will re-queue it.

To enable manual acknowledgment mode, set the noAck property to false:

  1. options: {
  2. urls: ['amqp://localhost:5672'],
  3. queue: 'cats_queue',
  4. noAck: false,
  5. queueOptions: {
  6. durable: false
  7. },
  8. },

When manual consumer acknowledgements are turned on, we must send a proper acknowledgement from the worker to signal that we are done with a task.

  1. @MessagePattern('notifications')
  2. getNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {
  3. const channel = context.getChannelRef();
  4. const originalMsg = context.getMessage();
  5. channel.ack(originalMsg);
  6. }
  1. @Bind(Payload(), Ctx())
  2. @MessagePattern('notifications')
  3. getNotifications(data, context) {
  4. const channel = context.getChannelRef();
  5. const originalMsg = context.getMessage();
  6. channel.ack(originalMsg);
  7. }