0.0.1 • Published 7 months ago
@madeweb/nestjs-service-bus v0.0.1
Description
Azure Service Bus is a fully managed enterprise message broker with message queues. Service Bus is used to decouple applications and services from each other, providing the following benefits:
- Load-balancing work across competing workers
- Safely routing and transferring data and control across service and application boundaries
- Coordinating transactional work that requires a high-degree of reliability
Installation
To start building Azure Service Bus-based microservices, first install the required packages:
$ npm i --save @azure/service-bus @madeweb/nestjs-service-busOverview
To use the Azure Service Bus strategy, pass the following options object to the createMicroservice() method:
// main.ts
const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
strategy: new AzureServiceBusServer({
connectionString: 'Endpoint=sb://<Name>.servicebus.windows.net/;SharedAccessKeyName=<SharedAccessKeyName>;SharedAccessKey=<SharedAccessKey>',
queueName: 'sample-queue',
}),
});Options
The Azure Service Bus strategy exposes the properties described below.
Usage
Add the following code to your main.ts file:
async function bootstrapAzureServiceBus(app: INestApplication): Promise<void> {
const serviceBusConnection = process.env.AZURE_SERVICE_BUS_CONNECTION;
if (serviceBusConnection) {
app.connectMicroservice<CustomStrategy>({
strategy: new AzureServiceBusStrategy({
connectionString: serviceBusConnection,
queueName: process.env.AZURE_SERVICE_BUS_DOWNLOAD_QUEUE,
}),
});
await app.startAllMicroservices();
}
}Producer
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AzureServiceBusClient } from '@madeweb/nestjs-service-bus';
import { firstValueFrom } from 'rxjs';
@Injectable()
export class AnyQueueService {
private client: AzureServiceBusClient;
private queueName: string;
constructor(private readonly configService: ConfigService) {
this.queueName = this.configService.get<string>(
'azureServiceBus.queueName',
);
this.client = new AzureServiceBusClient(
this.configService.get('azureServiceBus'),
);
}
public async sendMessage(body: string) {
await this.client.connect();
await firstValueFrom(this.client.emit(this.queueName, body));
}
}Consumer
To access the original Azure Service Bus message use the @MessagePattern decorator as follows:
@MessagePattern('AzureServiceBus')
async handleMessage(@Payload() data: string) {
console.log(`Received message: ${data}`);
}Options
Security concerns and contributions
- Author - Luis Benavides
License
Nestjs Azure Service Bus is MIT licensed.
0.0.1
7 months ago