Nats
Messaging with NATS
βοΈ Installation
npm install @nestjstools/messaging @nestjstools/messaging-nats-extension
or
yarn add @nestjstools/messaging @nestjstools/messaging-nats-extension
π¦ Overview
This guide demonstrates how to integrate NATS (and NATS JetStream) into a NestJS application using @nestjstools/messaging
and the messaging-nats-extension
.
We cover:
Basic NATS setup
Using JetStream
Message dispatch and handling
Cross-language messaging
Routing strategies
Configuration options
βοΈ Basic NATS Configuration
import { Module } from '@nestjs/common';
import { MessagingModule } from '@nestjstools/messaging';
import { MessagingNatsExtensionModule, NatsChannelConfig } from '@nestjstools/messaging-nats-extension';
@Module({
imports: [
MessagingNatsExtensionModule,
MessagingModule.forRoot({
buses: [
{
name: 'nats-message.bus',
channels: ['nats-message'],
},
],
channels: [
new NatsChannelConfig({
name: 'nats-message',
enableConsumer: true,
connectionUris: ['nats://localhost:4222'],
subscriberName: 'nats-core',
}),
],
debug: true,
}),
],
})
export class AppModule {}
π JetStream Configuration
import { Module } from '@nestjs/common';
import { MessagingModule } from '@nestjstools/messaging';
import { MessagingNatsExtensionModule, NatsJetStreamChannelConfig } from '@nestjstools/messaging-nats-extension';
@Module({
imports: [
MessagingNatsExtensionModule,
MessagingModule.forRoot({
buses: [
{
name: 'nats-message.bus',
channels: ['nats-channel-jetstream'],
},
],
channels: [
new NatsJetStreamChannelConfig({
name: 'nats-channel-jetstream',
connectionUris: ['nats://localhost:4222'],
enableConsumer: true,
streamConfig: {
streamName: 'event-steam',
deliverSubjects: ['my_app_command.*'],
autoUpdate: true,
},
consumerConfig: {
durableName: 'nats-durable_name',
subject: 'my_app_command.*',
autoUpdate: true,
},
}),
],
debug: true,
}),
],
})
export class AppModule {}
π€ Dispatching Messages
Use a controller to send messages through the bus.
import { Controller, Get } from '@nestjs/common';
import { CreateUser } from './application/command/create-user';
import { IMessageBus, MessageBus, RoutingMessage } from '@nestjstools/messaging';
@Controller()
export class AppController {
constructor(
@MessageBus('nats-message.bus') private natsMessageBus: IMessageBus,
) {}
@Get('/nats')
createUser(): string {
this.natsMessageBus.dispatch(
new RoutingMessage(new CreateUser('John FROM Nats'), 'my_app_command.create_user'),
);
return 'Message sent';
}
}
π₯ Handling Messages
Create a handler that listens to a specific routing key:
import { CreateUser } from '../create-user';
import {
IMessageHandler,
MessageHandler,
} from '@nestjstools/messaging';
@MessageHandler('my_app_command.create_user')
export class CreateUserHandler implements IMessageHandler<CreateUser> {
async handle(message: CreateUser): Promise<void> {
console.log(message);
// Your logic here
}
}
π Cross-Language Communication
To interact with NestJS handlers from external services (e.g., written in Go, Python, etc.):
Publish a message to the queue
Include the
messaging-routing-key
header
@MessageHandler('my_app_command.create_user') // <-- Use this as the routing key
Thatβs it! The NestJS app will route the message to the correct handler.
π§ Routing Strategy
Routing is determined by the subscriberName
or deliverSubjects
.
Static Routing
If subscriberName
is a concrete subject:
subscriberName = 'order.created';
// Message will be sent to 'order.created'
Wildcard Routing
If subscriberName
uses a wildcard:
subscriberName = 'order.*';
message.messageRoutingKey = 'order.created';
// Message will be sent to 'order.created'
JetStream Example
subject = 'order.*'; // from consumer
message.messageRoutingKey = 'order.created';
// The message will be published to 'order.created'
βοΈ Configuration Options
NatsChannelConfig
NatsChannelConfig
name
Name of the NATS channel (e.g., 'nats-message'
)
enableConsumer
Enable message consumption
connectionUris
NATS server URIs (e.g., ['nats://localhost:4222']
)
subscriberName
Unique identifier for the subscriber
π Note: JetStream and NATS offer extensive configurations. If this setup doesn't suit your needs, you can fork and customize the base channel classes provided in this package.
Last updated