0% found this document useful (0 votes)
12 views10 pages

RabbitMQ - Microservices - NestJS - A Progressive Node - Js Framework

The document provides an overview of using RabbitMQ as a message broker in NestJS microservices, detailing installation, configuration options, and message handling. It covers creating microservices and client instances, message acknowledgment, and accessing RabbitMQ context for message processing. Additionally, it discusses monitoring connection status and handling internal events within the microservice framework.

Uploaded by

ehenokh12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views10 pages

RabbitMQ - Microservices - NestJS - A Progressive Node - Js Framework

The document provides an overview of using RabbitMQ as a message broker in NestJS microservices, detailing installation, configuration options, and message handling. It covers creating microservices and client instances, message acknowledgment, and accessing RabbitMQ context for message processing. Additionally, it discusses monitoring connection status and handling internal events within the microservice framework.

Uploaded by

ehenokh12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

2/24/25, 1:28 PM RabbitMQ - Microservices | NestJS - A progressive Node.

js framework

dark_mode

https://docs.nestjs.com/microservices/rabbitmq 1/10
2/24/25, 1:28 PM RabbitMQ - Microservices | NestJS - A progressive Node.js framework

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:

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

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

main.ts JS

const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, { content_copy


transport: Transport.RMQ,
options: {
urls: ['amqp://localhost:5672'],
queue: 'cats_queue',
queueOptions: {
durable: false
},
},
});

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
https://docs.nestjs.com/microservices/rabbitmq 2/10
2/24/25, 1:28 PM
The options property is specific to theRabbitMQ - Microservices | NestJS - A progressive Node.js framework
chosen transporter. The RabbitMQ transporter exposes the properties
described below.

urls Connection urls

queue Queue name which your server will listen to

prefetchCount Sets the prefetch count for the channel

isGlobalPrefetchCount Enables per channel prefetching

noAck If false , manual acknowledgment mode enabled

consumerTag Consumer Tag Identifier (read more here)

queueOptions Additional queue options (read more here)

socketOptions Additional socket options (read more here)

headers Headers to be sent along with every message

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.

@Module({ content_copy
imports: [
ClientsModule.register([
https://docs.nestjs.com/microservices/rabbitmq 3/10
2/24/25, 1:28 PM RabbitMQ - Microservices | NestJS - A progressive Node.js framework
{
name: 'MATH_SERVICE',
transport: Transport.RMQ,
options: {
urls: ['amqp://localhost:5672'],
queue: 'cats_queue',
queueOptions: {
durable: false
},
},
},
]),
]
...
})

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

Context
In more complex scenarios, you may need to access additional information about the incoming request. When
using the RabbitMQ transporter, you can access the RmqContext object.

JS

@MessagePattern('notifications') content_copy
getNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {
console.log(`Pattern: ${context.getPattern()}`);
}

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:
https://docs.nestjs.com/microservices/rabbitmq 4/10
2/24/25, 1:28 PM RabbitMQ - Microservices | NestJS - A progressive Node.js framework

JS

@MessagePattern('notifications') content_copy
getNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {
console.log(context.getMessage());
}

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

JS

@MessagePattern('notifications') content_copy
getNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {
console.log(context.getChannelRef());
}

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 :

options: { content_copy
urls: ['amqp://localhost:5672'],
queue: 'cats_queue',
noAck: false,
queueOptions: {
durable: false
},
},

https://docs.nestjs.com/microservices/rabbitmq 5/10
2/24/25, 1:28 PM RabbitMQ - Microservices | NestJS - A progressive Node.js framework

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.

JS

@MessagePattern('notifications') content_copy
getNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {
const channel = context.getChannelRef();
const originalMsg = context.getMessage();

channel.ack(originalMsg);
}

Record builders
To configure message options, you can use the RmqRecordBuilder class (note: this is doable for event-based flows
as well). For example, to set headers and priority properties, use the setOptions method, as follows:

const message = ':cat:'; content_copy


const record = new RmqRecordBuilder(message)
.setOptions({
headers: {
['x-version']: '1.0.0',
},
priority: 3,
})
.build();

this.client.send('replace-emoji', record).subscribe(...);

HINT
RmqRecordBuilder class is exported from the @nestjs/microservices package.

And you can read these values on the server-side as well, by accessing the RmqContext , as follows:
https://docs.nestjs.com/microservices/rabbitmq 6/10
y
2/24/25, 1:28 PM y g
RabbitMQ - Microservices | NestJS - A progressive Node.js framework

JS

@MessagePattern('replace-emoji') content_copy
replaceEmoji(@Payload() data: string, @Ctx() context: RmqContext): string {
const { properties: { headers } } = context.getMessage();
return headers['x-version'] === '1.0.0' ? ' 🐱 ' : '🐈 ' ;
}

Instance status updates


To get real-time updates on the connection and the state of the underlying driver instance, you can subscribe to the
status stream. This stream provides status updates specific to the chosen driver. For the RMQ driver, the status
stream emits connected and disconnected events.

this.client.status.subscribe((status: RmqStatus) => { content_copy


console.log(status);
});

HINT
The RmqStatus type is imported from the @nestjs/microservices package.

Similarly, you can subscribe to the server's status stream to receive notifications about the server's status.

const server = app.connectMicroservice<MicroserviceOptions>(...); content_copy


server.status.subscribe((status: RmqStatus) => {
console.log(status);
});

Listening to RabbitMQ events


In some cases, you might want to listen to internal events emitted by the microservice. For example, you could
li f h i
https://docs.nestjs.com/microservices/rabbitmq ddi i l i h d hi h () h d 7/10
2/24/25, 1:28 PM RabbitMQ - Microservices | NestJS - A progressive Node.js framework
listen for the error event to trigger additional operations when an error occurs. To do this, use the on() method,
as shown below:

this.client.on('error', (err) => { content_copy


console.error(err);
});

Similarly, you can listen to the server's internal events:

server.on<RmqEvents>('error', (err) => { content_copy


console.error(err);
});

HINT
The RmqEvents type is imported from the @nestjs/microservices package.

Underlying driver access


For more advanced use cases, you may need to access the underlying driver instance. This can be useful for
scenarios like manually closing the connection or using driver-specific methods. However, keep in mind that for
most cases, you shouldn't need to access the driver directly.

To do so, you can use the unwrap() method, which returns the underlying driver instance. The generic type
parameter should specify the type of driver instance you expect.

const managerRef = content_copy


this.client.unwrap<import('amqp-connection-manager').AmqpConnectionManager>();

Similarly, you can access the server's underlying driver instance:

const managerRef = content_copy


i ('
https://docs.nestjs.com/microservices/rabbitmq
i ') A C i M () 8/10
2/24/25, 1:28 PM RabbitMQ - Microservices | NestJS - A progressive Node.js framework
server.unwrap<import('amqp-connection-manager').AmqpConnectionManager>();

Support us
Nest is an MIT-licensed open source project. It can grow thanks to the support by these awesome people. If you'd
like to join them, please read more here.

Principal Sponsors Sponsors / Partners

Become a sponsor

Join our Newsletter


Subscribe to stay up to date with the latest Nest updates, features, and videos!

Email address..

Copyright © 2017-2025 MIT by Kamil Mysliwiec design by Jakub Staron


Official NestJS Consulting Trilon.io hosted by Netlify

https://docs.nestjs.com/microservices/rabbitmq 9/10
2/24/25, 1:28 PM RabbitMQ - Microservices | NestJS - A progressive Node.js framework

https://docs.nestjs.com/microservices/rabbitmq 10/10

You might also like