nats-io / stan.go

NATS Streaming System
https://nats.io
Apache License 2.0
706 stars 117 forks source link

didn't find a way to reconnect. Please help me ! #332

Closed artem-webdev closed 3 years ago

artem-webdev commented 3 years ago

there is such a code in a real project clientId cannot be changed !!! how can I reconnect if I get in response - stan: clientID already registered ?

package main

import (
    "github.com/nats-io/stan.go"
    "log"
)

const (
    StanServers   = "host-1:4222,host-2:4222,host-3:4222"
    StanClusterId = "queue-messages"
)

func GetConnectStan(clientId string) (stan.Conn, error) {

    conn, err := stan.Connect(
        StanClusterId,
        clientId,
        stan.NatsURL(StanServers),
        stan.Pings(5, 10),
        stan.SetConnectionLostHandler(func(_ stan.Conn, reason error) {
            log.Fatal(reason.Error())

        }),
    )

    return conn, err

}

type ServiceProxy struct {
    NatsConn stan.Conn
}

func main() {

    proxy := ServiceProxy{}
    var err error
    proxy.NatsConn, err = GetConnectStan("test-client-1")
    if err != nil {
        log.Fatal(err.Error(), proxy.NatsConn)
    }

    //for some unknown reason, the pointer became nil
    proxy.NatsConn = nil

        // return fail stan: clientID already registered
    if proxy.NatsConn == nil {
        proxy.NatsConn, err = GetConnectStan("test-client-1")
        if err != nil {
            log.Fatal(err.Error(), proxy.NatsConn)
        }
    }

}
kozlovic commented 3 years ago

@artem-webdev This behavior is expected: the original connection is not closed/lost, you just try to create a new connection with the same client ID, which the server will reject because it can reach the first one (will send an heartbeat and get a response). Had it be 2 different processes and the first would have exited, then reusing the same client ID would work. https://docs.nats.io/nats-streaming-concepts/client-connections