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.
To start building NATS-based microservices, first install the required package:
To use the NATS transporter, pass the following options object to the
info Hint The
Transportenum is imported from 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.
Like other microservice transporters, you have several options for creating a NATS
One method for creating an instance is to use 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
Other options to create a client (either
@Client()) can be used as well. You can read about them here.
For the request-response message style (read more), the NATS transporter uses NATS built-in Request-Reply mechanism. A request is published on a given subject with a reply subject, and responders listen on that subject and send responses to the reply subject. Reply subjects are usually a subject called an
_INBOX that will be directed back to the requestor dynamically, regardless of location of either party.
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.
NATS provides a built-in load balancing feature called distributed queues. To create a queue subscription, use the
queue property as follows:
In more sophisticated scenarios, you may want to access more information about the incoming request. When using the NATS transporter, you can access the
NatsContextare imported from the
A subscription may be to an explicit subject, or it may include wildcards.