g14u
g14u

Reputation: 247

How to loop NATS messages received over channel

I have a code like that:

package main


import (
    "fmt"

    "github.com/nats-io/nats.go"
)

func main()  {
    nc, _ := nats.Connect(nats.DefaultURL)
    for {
        nc.Subscribe("request", func(m *nats.Msg) {
            fmt.Printf("Received a message: %s\n", string(m.Data))
            m.Respond([]byte("Received"))
        })
    }
}

What I try to do is receive a message and after receiving a message send a reply to message, forever as shown in the example.

However with the code above, there are some problems. When I added for {to the code, it repeats the same message until a new message is received.

What is the correct implementation to receive messages continuously with NATS? (Without replying received messages)

Upvotes: 0

Views: 2171

Answers (1)

mri1939
mri1939

Reputation: 306

It looks like you would be ended up with an unlimited subscription to the subject. You only need to call the Subscribe method once.

Firstly, the method Subscribe is returning something and we should save the value from the Subscribe(...) method.

s, err := nc.Subscribe(subj, msgHandler)
// handle err
for {
 // if something happened, quit the loop
}
s.Unsubscribe()

The msgHandle will be called when there are new messages on the subj. So you just have to wait. And you could be waiting with infinite loop after creating a subscription.

However, I think it is better to do a subscription using a channel.

// Channel Subscriber
ch := make(chan *nats.Msg, 64)
sub, err := nc.ChanSubscribe("foo", ch)
// handle err
for msg := range ch {
    // do something to the nats.Msg object
}
// Unsubscribe if needed
sub.Unsubscribe()
close(ch)

Please consider reading the documentation here.

Upvotes: 3

Related Questions