A comprehensive RabbitMQ module for NestJS applications, providing easy integration with RabbitMQ for microservices communication.
npm install ecom-rabbitmq
Before using the module, make sure to set the RABBITMQ_URLS
environment variable with your RabbitMQ server URLs. You can set this in your .env
file:
RABBITMQ_URLS=amqp://localhost:5672
To use the RabbitMQ module in your NestJS application, import it in your app module:
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { RabbitMQModule } from 'ecom-rabbitmq';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [
ConfigModule.forRoot(),
RabbitMQModule.forRootAsync({
isGlobal: true,
useFactory: async () => ({
uris: ['amqp://localhost:5672'],
encryptionKey: 'secret',
queue: 'test-queue',
}),
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
To send messages (when you expect a response), use the send
method:
import { Injectable } from '@nestjs/common';
import { RabbitMQService } from 'ecom-rabbitmq';
@Injectable()
export class AppService {
constructor(private readonly rabbitMqService: RabbitMQService) {}
getHello(): string {
this.rabbitMqService.sendToQueue('merchant', 'hello', {
deliveryMode: true,
persistent: true,
});
return 'Hello World!';
}
}
-
forRootAsync(options: IRabbitMQModuleAsyncOptions): DynamicModule
Creates a global asynchronous RabbitMQ module.
-
consume(queue: string | null, onMessage: (msg: any) => void, options?: ConsumerOptions): Promise<Replies.Consume>
Starts consuming messages from a queue.
-
sendToQueue(queue: string | null, message: Buffer | string, secure?: boolean, options?: PublishOptions, done?: () => boolean): Promise<boolean>
Sends a message to a queue.
-
publish(exchange: string, routingKey: string, content: Buffer | string | any, secure?: boolean, options?: PublishOptions, done?: () => boolean): Promise<boolean>
Publishes a message to an exchange.
-
acknowledgeMessage(message: Message, allUpTo?: boolean): void
Acknowledges a message.