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:

  1. @@filename(main)
  2. const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
  3. transport: Transport.RMQ,
  4. options: {
  5. urls: ['amqp://localhost:5672'],
  6. queue: 'cats_queue',
  7. queueOptions: {
  8. durable: false
  9. },
  10. },
  11. });
  12. @@switch
  13. const app = await NestFactory.createMicroservice(AppModule, {
  14. transport: Transport.RMQ,
  15. options: {
  16. urls: ['amqp://localhost:5672'],
  17. queue: 'cats_queue',
  18. queueOptions: {
  19. durable: false
  20. },
  21. },
  22. });

info 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 ClientsModule here.

  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. @@filename()
  2. @MessagePattern('notifications')
  3. getNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {
  4. console.log(`Pattern: ${context.getPattern()}`);
  5. }
  6. @@switch
  7. @Bind(Payload(), Ctx())
  8. @MessagePattern('notifications')
  9. getNotifications(data, context) {
  10. console.log(`Pattern: ${context.getPattern()}`);
  11. }

info 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. @@filename()
  2. @MessagePattern('notifications')
  3. getNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {
  4. console.log(context.getMessage());
  5. }
  6. @@switch
  7. @Bind(Payload(), Ctx())
  8. @MessagePattern('notifications')
  9. getNotifications(data, context) {
  10. console.log(context.getMessage());
  11. }

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

  1. @@filename()
  2. @MessagePattern('notifications')
  3. getNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {
  4. console.log(context.getChannelRef());
  5. }
  6. @@switch
  7. @Bind(Payload(), Ctx())
  8. @MessagePattern('notifications')
  9. getNotifications(data, context) {
  10. console.log(context.getChannelRef());
  11. }

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. @@filename()
  2. @MessagePattern('notifications')
  3. getNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {
  4. const channel = context.getChannelRef();
  5. const originalMsg = context.getMessage();
  6. channel.ack(originalMsg);
  7. }
  8. @@switch
  9. @Bind(Payload(), Ctx())
  10. @MessagePattern('notifications')
  11. getNotifications(data, context) {
  12. const channel = context.getChannelRef();
  13. const originalMsg = context.getMessage();
  14. channel.ack(originalMsg);
  15. }