Home > Blockchain >  How to receive heart beat messages from NATS Jetstream server
How to receive heart beat messages from NATS Jetstream server

Time:10-20

I have a running local NATS server with a stream named EVENTS and several subjects.

In Golang, I am trying to subscribe with a push consumer using the idleHeartBeat option as described here.

I searched a lot online and could not find a way to receive these heart beats. Initially, I thought I was going to receive them as regular messages (as I understood from here), but when running the code below I only receive the messages I publish and no heart beats. This happens even though after receiving all messages I published and waiting a few seconds there are no messages to be sent anymore.

Is there any other configuration I should do? Should I listen from another subscription or specific subject?

I would really appreciate any guidance to how to receive these heart beats messages in Golang and process them in some way.

This is my code:

    func main() {

    url := os.Getenv("NATS_URL")
    if url == "" {
        url = nats.DefaultURL
    }

    nc, _ := nats.Connect(url)
    defer nc.Drain()

    js, _ := nc.JetStream()

    streamName := "EVENTS"

    js.AddStream(&nats.StreamConfig{
        Name:     streamName,
        Subjects: []string{"events.>"},
    })

    js.Subscribe("events.*", func(msg *nats.Msg) {
        fmt.Printf("monitor service subscribes from subject:%s\n", msg.Subject)
        fmt.Printf("received %q from my subscription\n", msg.Subject)
        msg.Ack()
    }, nats.IdleHeartbeat(1*time.Second), nats.DeliverLast(), nats.ManualAck())

    for {

    }
}

Thanks in advance!

CodePudding user response:

In the article you linked, the creation of the consumer and the subscription to the consumer is made through the CLI. In the CLI, the client just receives all messages, even the heartbeats.

The NATS Go client works differently. When you call the Subscribe function, it creates a consumer (since you didn't define it previously) and subscribes to it. The messages published to the stream (and the consumer) are delivered to your message handlers, but the heartbeats are handled automatically (check the source code). This is also described in the documentation you linked:

Note that this heartbeat mechanism is all handled transparently by supported clients and does not need to be handled by the application.

To sum up, the CLI client shows all the messages coming through the subscribed topic, whereas the NATS Go client handles the heartbeats automatically and you don't see them in your message handlers.

  • Related