nats-io / stan.go

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

How to make clientid dynamic in StatefulSets replicas: 3 in kubernetes #335

Closed alifpay closed 3 years ago

alifpay commented 3 years ago

Hi, I have issue clientID in Kubernetes replicas. How to make clientID in dynamic for stan connection if i have replicas more than 1 in Kubernetes?


sc, err := stan.Connect(clusterid, clientID, stan.NatsConn(nc))

durableOpt := stan.DurableName("servicename")

_, err = sc.QueueSubscribe("pay", "groupName", fnPay, durableOpt)

DurableName must be different or same for each connection in QueueSubscribe ?

kozlovic commented 3 years ago

DurableName must be different or same for each connection in QueueSubscribe ?

My answer would be no, but not sure what you are trying to do. Here is some info on durables and queue (durables or not): https://docs.nats.io/nats-streaming-concepts/channels/subscriptions/durable https://docs.nats.io/nats-streaming-concepts/channels/subscriptions/queue-group

For queue groups, the clientID does not have to be the same when you restart an application. Since a single connection with the same clientID can exist at one point it time, it would prevent several applications to participate in the same group. So you could use a generated unique ID for this application.

wallyqs commented 3 years ago

Hi @alifpay I might be misunderstanding but what you can do is to use the POD_NAME environment variable from K8S to get a predictable name for the clientID.

sc, err := stan.Connect(clusterid, os.Getenv("POD_NAME"), stan.NatsConn(nc))

This will work better if you use a StatefulSet instead of a Deployment, so that when your pod gets restarted it will use the same name.

alifpay commented 3 years ago

thank you! very much