Connect to NATS
To connect to NATS it is necessary to use a client. NATS provides a Golang client that you can use to write a simple NATS client.
A client can produce or consume messages on a NATS subscription. This section describes how to write a client that allows us both to produce and consume messages. To do so, follow the steps below:
IMPORTANT: To follow the steps below, you need to have the Go environment set up. See the Go official documentation to learn how to install Go.
-
Obtain the NATS server authentication credentials.
-
Install the nats-pub and nats-echo client examples as shown below:
$ GO111MODULE=off go get github.com/nats-io/nats.go $ cd $GOPATH/src/github.com/nats-io/nats.go/examples/nats-pub && go install && cd - $ cd $GOPATH/src/github.com/nats-io/nats.go/examples/nats-echo && go install && cd -
-
Use the nats-echo client to create a subscriber. Replace the PASSWORD placeholder with the credentials you have obtained in the NATS authentication section:
$ nats-echo -s nats://nats:PASSWORD@127.0.0.1:4222 SomeSubject
-
Use the nats-pub client to send a message to the subject “foo”. Replace the PASSWORD placeholder with the credentials you have obtained in the NATS authentication section:
$ nats-pub -s nats://nats:PASSWORD@127.0.0.1:4222 -reply Hi SomeSubject "Hi everyone" Connected to NATS server: nats://127.0.0.1:4222 Published [SomeSubject] : 'Hi everyone'
-
You should see the confirmation of the subscriber is receiving the messages:
Listening on [SomeSubject] ... Received message 'Hi everyone'
To learn more about the use of this and other clients, check NATS official documentation and NATS GitHub repository.