Pub/Sub Walkthrough
Last updated
Last updated
NATS is a publish subscribe messaging system based on subjects. Subscribers listening on a subject receive messages published on that subject. If the subscriber is not actively listening on the subject, the message is not received. Subscribers can use the wildcard tokens such as *
and >
to match a single token or to match the tail of a subject.
This simple walkthrough demonstrates some ways in which subscribers listen on subjects, and publishers send messages on specific subjects.
If you have not already done so, you need to install the nats
CLI Tool and optionally the nats-server on your machine.
In a shell or command prompt session, start a client subscriber program.
Here, <subject>
is a subject to listen on. It helps to use unique and well thought-through subject strings because you need to ensure that messages reach the correct subscribers even when wildcards are used.
For example:
You should see the message: Listening on [msg.test]
In another shell or command prompt, create a NATS publisher and send a message.
Where <subject>
is the subject name and <message>
is the text to publish.
For example:
You'll notice that the publisher sends the message and prints: Published [msg.test] : 'NATS MESSAGE'.
The subscriber receives the message and prints: [#1] Received on [msg.test]: 'NATS MESSAGE'.
If the receiver does not get the message, you'll need to check if you are using the same subject name for the publisher and the subscriber.
You'll notice that the subscriber receives the message. Note that a message count is incremented each time your subscribing client receives a message on that subject.
In a new shell or command prompt, start a new NATS subscriber.
Verify that both subscribing clients receive the message.
In a new shell or command prompt session, create a new subscriber that listens on a different subject.
Subscriber 1 and Subscriber 2 receive the message, but Subscriber 3 does not. Why? Because Subscriber 3 is not listening on the message subject used by the publisher.
Change the last subscriber to listen on msg.* and run it:
Note: NATS supports the use of wildcard characters for message subscribers only. You cannot publish a message using a wildcard subject.
This time, all three subscribing clients should receive the message.
Do try out a few more variations of substrings and wildcards to test your understanding.
Publish-subscribe pattern with the NATS CLI