RabbitMQ library
This library is responsible for handling RabbitMQ connection, message production and consumption.
Dependencies
Package | Version |
---|---|
amqplib | ^0.10.3 |
@nestjs/common | ^10.0.0 |
@nestjs/core | ^10.0.0 |
@nestjs/terminus | ^10.0.0 |
reflect-metadata | <1.0.0 |
rxjs | ^7.0.0 |
Usage
- To start using this library simply import
RabbitMqModule
to your module.
@Module({
imports: [
RabbitMqModule.forFeature({
uri: 'amqp://test:test@localhost:5672/',
prefetchSize: 10,
parser: ProtoMessageParserService,
}, 'my-handle'),
]
})
export class AppModule {
// ...
}
- Prepare rabbit environment setup
import { Injectable } from '@nestjs/common';
import { InjectConfig, InjectConnectionUtils } from '@betsys-nestjs/rabbit-mq';
import { RabbitMqConfig } from '@betsys-nestjs/rabbit-mq';
import { AbstractSetupRabbitEnvironmentService } from '@betsys-nestjs/rabbit-mq';
import { RabbitMqConnectionUtils } from '@betsys-nestjs/rabbit-mq';
@Injectable()
export class SetupRabbitEnvironmentService extends AbstractSetupRabbitEnvironmentService {
constructor(
@InjectConnectionUtils()
private readonly rabbitMqConnectionUtils: RabbitMqConnectionUtils,
@InjectConfig() private config: RabbitMqConfig,
) {
super();
}
protected async setup(): Promise<void> {
await this.rabbitMqConnectionUtils.createExchange(
'my-exchange',
'direct',
{
durable: true,
autoDelete: false,
internal: false,
arguments: {},
},
);
await this.rabbitMqConnectionUtils.createQueue(
'my-queue',
{
durable: true,
autoDelete: false,
maxLength: 100000,
},
);
await this.rabbitMqConnectionUtils.bindQueue(
'result-queue',
'result-exchange',
'my-routing-key',
);
}
}
and set it up
async onApplicationBootstrap(): Promise<void> {
await this.setupRabbit.execute();
}
Proto message parser
Furthermore you need to implement proto-message parser class that extends AbstractProtoMessageParserService
, and implements MessageParser
and pass it to the forFeature
static method to the parser
property of RabbitMqModule
.
Example of implementing ProtoMessageParser
:
import path from 'path';
import { Injectable } from '@nestjs/common';
import { loadSync, Type } from 'protobufjs';
import { AbstractProtoMessageParserService } from '@betsys-nestjs/rabbit-mq';
import { InjectLogger } from '@betsys-nestjs/rabbit-mq';
import { RabbitMqLoggerInterface } from '@betsys-nestjs/rabbit-mq';
import { MessageParser } from '@betsys-nestjs/rabbit-mq';
export interface UpdateMessage {
table: string;
uuid: string;
timestamp: bigint;
}
export interface ProtoMessage {
table: string | null;
uuid: string | null;
timestamp: number | null;
}
export interface ProtoMessageBulk {
messages: ProtoMessage[];
}
@Injectable()
export class ProtoMessageParserService extends AbstractProtoMessageParserService<
UpdateMessage,
ProtoMessage,
ProtoMessageBulk,
Type
> implements MessageParser {
constructor(@InjectLogger() protected logger: RabbitMqLoggerInterface) {
super(logger);
}
protected createRowMessageBulkDecoder(): Type {
const protoRoot = loadSync(path.join(__dirname, './update_message.proto'));
return protoRoot.lookupType('updatemessage.RowMessageBulk');
}
protected transformPayload(protoMessage: ProtoMessage): UpdateMessage {
return {
table: protoMessage.table || '',
uuid: protoMessage.uuid || '',
// timestamp after decoding has inaccuracy 100 nanoseconds (it means 2 last places are replaced by zeroes)
timestamp: protoMessage.timestamp || 0n,
} as UpdateMessage;
}
}
- Then you can produce messages:
await rabbitMqProduceUtils.publishToExchange(
'test-exchange',
'test-routing-key',
Buffer.from(
JSON.stringify({
message: 'My message',
}),
),
);
- Or consume messages:
await rabbitMqConsumeUtils.consumeQueueSync('my-queue', async (message: ConsumeMessage) => {
// do something with message
});
Monitoring and Logger
The library is ready to work with monitoring and logger. To enable it you need to implement your own monitoring and logger service based on abstraction provided by this library.
Monitoring
There are three different monitoring parts that can be independently set in the config:
Time monitoring - used for monitoring of operation time and message time, your provided service must implement RabbitMqTimeMonitoringInterface
. Implementation of startTimerOperationTime
starts your custom timer returning a function which stops the timer, similarly the implementation of startTimerMessageTime
.
Connection monitoring - used for observing count of connections to rabbit-mq via this library. To use this monitoring type, you must implement RabbitMqConnectionMonitoringInterface
.
Message count monitoring - used for observing counts of messages. To use this monitoring type, you must implement RabbitMqMessageCountMonitoringInterface
.
Example of connection monitoring using @betsys-nestjs/monitoring
:
import cluster from 'cluster';
import {
Gauge,
InjectMonitoringConfig,
InjectMonitoringRegistry,
Registry,
AbstractMonitoringService,
MonitoringConfigInterface,
} from '@betsys-nestjs/monitoring';
import { RabbitMqConnectionMonitoringInterface } from '@betsys-nestjs/rabbit-mq';
export class RabbitMqMonitoringService extends AbstractMonitoringService implements
RabbitMqConnectionMonitoringInterface {
private readonly SYSTEM_LABEL = 'rabbitmq';
private readonly connectionGauge: Gauge<string>;
private readonly workerId: number;
constructor(
@InjectMonitoringConfig() private readonly config: MonitoringConfigInterface,
@InjectMonitoringRegistry() protected readonly registry: Registry,
) {
super(registry);
this.connectionGauge = super.createMetric(Gauge, {
name: this.config.getMetricsName('open_connection'),
help: 'count of currently open connections to rabbitmq',
labelNames: ['system', 'handle'],
registers: [registry],
});
this.workerId = RabbitMqMonitoringService.getWorkerId();
}
private static getWorkerId(): number {
return cluster.isMaster ? 0 : cluster.worker?.id ?? -1;
}
connectionOpened(handle: string): void {
this.connectionGauge.inc({ system: this.SYSTEM_LABEL, handle }, 1);
}
connectionClosed(handle: string): void {
this.connectionGauge.dec({ system: this.SYSTEM_LABEL, handle }, 1);
}
}
Logger
Similarly to monitoring you can simply implement custom service following RabbitMqLoggerInterface
.
import { RabbitMqLoggerInterface } from '@betsys-nestjs/rabbit-mq';
import { Logger as NestLogger } from '@betsys-nestjs/logger';
export class RabbitLoggerService implements RabbitMqLoggerInterface {
constructor(private readonly logger: NestLogger) {}
setContext(context: string): void {
this.logger.setContext(context);
}
debug(message: string) {
this.logger.debug(message);
}
error(message: string) {
this.logger.error(message);
}
}
To start using Logger
or Monitoring
service, you simply insert class references to forFeature
method of PostgresModule
like this:
RabbitMqModule.forFeature({
// other config values,
logger: RabbitMqTestLogger,
monitoring: {
connection: TestConnectionMonitoringService,
time: TestTimeMonitoringService,
messageCount: TestMessageCountMonitoringService,
},
})