Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve Nats Client Connection Logic #862

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions clients/messaging/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,22 +30,30 @@ func NewClient(name, natsURL string) *Client {
nc *nats.Conn
err error
)
for i := 0; i < 10; i++ {
nc, err = nats.Connect(natsURL)
if err == nil {
break
}
logger.WithError(err).Error("failed to connect to nats server")
time.Sleep(time.Second * 1) // don't retry too quickly - maybe it's not up yet
}
nc, err = nats.Connect(natsURL,
nats.ReconnectWait(2*time.Second),
nats.MaxReconnects(10),
nats.DisconnectErrHandler(func(nc *nats.Conn, err error) {
fmt.Printf("Got disconnected! Reason: %s\n", err.Error())
}),
nats.ReconnectHandler(func(nc *nats.Conn) {
fmt.Printf("Got reconnected to %v!\n", nc.ConnectedUrl())
}),
nats.ClosedHandler(func(nc *nats.Conn) {
fmt.Printf("Connection closed. Reason: %s", nc.LastError().Error())
}),
)

if err != nil {
logger.Panic(err)
logger.Panic(fmt.Errorf("failed to connect to nats server %w", err))
}

logger.Info("successfully connected")
client := &Client{
logger: logger,
nc: nc,
}

return client
}

Expand Down