NATS Logo by Example

Core Publish-Subscribe in Messaging

This example demonstrates the core NATS publish-subscribe behavior. This is the fundamental pattern that all other NATS patterns and higher-level APIs build upon. There are a few takeaways from this example:

  • Delivery is an at-most-once. For MQTT users, this is referred to as Quality of Service (QoS) 0.
  • There are two circumstances when a published message won’t be delivered to a subscriber:
    • The subscriber does not have an active connection to the server (i.e. the client is temporarily offline for some reason)
    • There is a network interruption where the message is ultimately dropped
  • Messages are published to subjects which can be one or more concrete tokens, e.g. greet.bob. Subscribers can utilize wildcards to show interest on a set of matching subjects.
$ nbe run messaging/pub-sub/cli
View the source code or learn how to run this example yourself

Code

#!/bin/sh

The nats CLI utilizes the NATS_URL environment variable if set. However, if you want to manage different contexts for connecting or authenticating, check out the nats context commands. For example:

nats context save --server=$NATS_URL local
NATS_URL="${NATS_URL:-nats://localhost:4222}"

Publish a message to the subject ‘greet.joe’. Nothing will happen since the subscription is not yet setup.

nats pub 'greet.joe' 'hello'

Let’s start a subscription in the background that will print the output to stdout.

nats sub 'greet.*' &

This just captures the process ID of the previous command in this shell.

SUB_PID=$!

Tiny sleep to ensure the subscription connected.

sleep 0.5

Now we can publish a couple times..

nats pub 'greet.joe' 'hello'
nats pub 'greet.pam' 'hello'
nats pub 'greet.bob' 'hello'

Remove the subscription.

kill $SUB_PID

Publishing again will not result in anything.

nats pub 'greet.bob' 'hello'

Output

13:57:13 Published 5 bytes to "greet.joe"
13:57:13 Subscribing on greet.* 
13:57:13 Published 5 bytes to "greet.joe"
[#1] Received on "greet.joe"
hello

13:57:13 Published 5 bytes to "greet.pam"
[#2] Received on "greet.pam"
hello

13:57:13 Published 5 bytes to "greet.bob"
[#3] Received on "greet.bob"
hello

13:57:13 Published 5 bytes to "greet.bob"

Recording

Note, playback is half speed to make it a bit easier to follow.