Skip to content

Instantly share code, notes, and snippets.

@charbonnierg
Last active December 22, 2023 10:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charbonnierg/250b96e2b207e2a03129b257ff0bf3d8 to your computer and use it in GitHub Desktop.
Save charbonnierg/250b96e2b207e2a03129b257ff0bf3d8 to your computer and use it in GitHub Desktop.
NATS CLI Cheatsheet

NATS Cheatsheet

Cheat sheets are available from the CLI directly:

nats cheat

Try out the following commands:

nats cheat contexts
nats cheat pub

Contexts

  • Create a non-default context:
nats context add development --server nats.dev.example.net:4222
  • Create a new default context:
nats context add development --server nats.dev.example.net:4222 --select
  • Update (you can choose the editor of your choice)
EDITOR=vim nats context edit development
  • List contexts
nats context ls
  • View context
nats context info development
  • View context in JSON format:
nats context info development --json
  • Validate all connections are valid and that connections can be established:
nats context validate --connect
  • Select a new default context:
nats context select development

Publish

  • Publish using the default context:
nats pub subject body

Where subject is the message subject, and `body`` is the message body

  • Publish using a different context than the default context:
nats pub --context development subject body
  • To publish 100 messages with a random body between 100 and 1000 characters:
nats pub destination.subject "{{ Random 100 1000 }}" -H Count:{{ Count }} --count 100
  • To publish messages from STDIN:
echo "hello world" | nats pub destination.subject

Requests

  • To send a request and wait for response:
nats req subject request

Where subject is the subject where request will be sent, and request is the request payload.

  • To request a response from a server and show just the raw result:
nats request destination.subject "hello world" -H "Content-type:text/plain" --raw

Replies

  • To set up a responder that runs an external command with the 3rd subject token as argument:
nats reply "service.requests.>" --command "service.sh {{2}}"
  • To set up basic responder:
nats reply service.requests "Message {{Count}} @ {{Time}}"
  • To setup an echo responder:
nats reply service.requests --echo --sleep 10
@BrahimS
Copy link

BrahimS commented Dec 22, 2023

Thanks Guillaume 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment