NATS

NATS is a simple, secure and high performance open source messaging system for cloud native applications, IoT messaging, and microservices architectures. The NATS server is written in the Go programming language, but client libraries to interact with the server are available for dozens of major programming languages. NATS supports both At Most Once and At Least Once delivery. It can run anywhere, from large servers and cloud instances, through edge gateways and even Internet of Things devices.

Installation

To start building NATS-based microservices, first install the required package:

  1. $ npm i --save nats

Overview

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

  1. @@filename(main)
  2. const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
  3. transport: Transport.NATS,
  4. options: {
  5. servers: ['nats://localhost:4222'],
  6. },
  7. });
  8. @@switch
  9. const app = await NestFactory.createMicroservice(AppModule, {
  10. transport: Transport.NATS,
  11. options: {
  12. servers: ['nats://localhost:4222'],
  13. },
  14. });

info Hint The Transport enum is imported from the @nestjs/microservices package.

Options

The options object is specific to the chosen transporter. The NATS transporter exposes the properties described here. Additionally, there is a queue property which allows you to specify the name of the queue that your server should subscribe to (leave undefined to ignore this setting). Read more about NATS queue groups below.

Client

Like other microservice transporters, you have several options for creating a NATS 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.

  1. @Module({
  2. imports: [
  3. ClientsModule.register([
  4. {
  5. name: 'MATH_SERVICE',
  6. transport: Transport.NATS,
  7. options: {
  8. servers: ['nats://localhost:4222'],
  9. }
  10. },
  11. ]),
  12. ]
  13. ...
  14. })

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

Request-response

For the request-response message style (read more), the NATS transporter does not use the NATS built-in Request-Reply mechanism. Instead, a “request” is published on a given subject using the publish() method with a unique reply subject name, and responders listen on that subject and send responses to the reply subject. Reply subjects are directed back to the requestor dynamically, regardless of location of either party.

Event-based

For the event-based message style (read more), the NATS transporter uses NATS built-in Publish-Subscribe mechanism. A publisher sends a message on a subject and any active subscriber listening on that subject receives the message. Subscribers can also register interest in wildcard subjects that work a bit like a regular expression. This one-to-many pattern is sometimes called fan-out.

Queue groups

NATS provides a built-in load balancing feature called distributed queues. To create a queue subscription, use the queue property as follows:

  1. @@filename(main)
  2. const app = await NestFactory.createMicroservice(AppModule, {
  3. transport: Transport.NATS,
  4. options: {
  5. servers: ['nats://localhost:4222'],
  6. queue: 'cats_queue',
  7. },
  8. });

Context

In more sophisticated scenarios, you may want to access more information about the incoming request. When using the NATS transporter, you can access the NatsContext object.

  1. @@filename()
  2. @MessagePattern('notifications')
  3. getNotifications(@Payload() data: number[], @Ctx() context: NatsContext) {
  4. console.log(`Subject: ${context.getSubject()}`);
  5. }
  6. @@switch
  7. @Bind(Payload(), Ctx())
  8. @MessagePattern('notifications')
  9. getNotifications(data, context) {
  10. console.log(`Subject: ${context.getSubject()}`);
  11. }

info Hint @Payload(), @Ctx() and NatsContext are imported from the @nestjs/microservices package.

Wildcards

A subscription may be to an explicit subject, or it may include wildcards.

  1. @@filename()
  2. @MessagePattern('time.us.*')
  3. getDate(@Payload() data: number[], @Ctx() context: NatsContext) {
  4. console.log(`Subject: ${context.getSubject()}`); // e.g. "time.us.east"
  5. return new Date().toLocaleTimeString(...);
  6. }
  7. @@switch
  8. @Bind(Payload(), Ctx())
  9. @MessagePattern('time.us.*')
  10. getDate(data, context) {
  11. console.log(`Subject: ${context.getSubject()}`); // e.g. "time.us.east"
  12. return new Date().toLocaleTimeString(...);
  13. }