Skip to content

Commit 9c11fb3

Browse files
author
David Arnold
authored
Implement (dump) NATS reconnection attempts on startup (#38)
fixes #37
1 parent 1a170bf commit 9c11fb3

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

server/server.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,14 @@ import (
1616
"github.com/pkg/errors"
1717
)
1818

19+
// DefaultReconnectionAttemts is the default number of reconnection attempts
20+
// It implements a hard coded fault tolerance for a starting NATS cluster
21+
const DefaultNATSReconnectionAttemts = 5
22+
23+
// DefaultNATSReconnectionWait is the default wating time between each reconnection
24+
// attempt
25+
const DefaultNATSReconnectionWait = 5 * time.Second
26+
1927
// Server describes the asterisk-facing ARI proxy server
2028
type Server struct {
2129
// Application is the name of the ARI application of this server
@@ -73,6 +81,13 @@ func (s *Server) Listen(ctx context.Context, ariOpts *native.Options, natsURI st
7381

7482
// Connect to NATS
7583
nc, err := nats.Connect(natsURI)
84+
reconnectionAttempts := DefaultNATSReconnectionAttemts
85+
for err == nats.ErrNoServers && reconnectionAttempts > 0 {
86+
s.Log.Info("retrying to connect to NATS server", "attempts", reconnectionAttempts)
87+
time.Sleep(DefaultNATSReconnectionWait)
88+
nc, err = nats.Connect(natsURI)
89+
reconnectionAttempts -= 1
90+
}
7691
if err != nil {
7792
return errors.Wrap(err, "failed to connect to NATS")
7893
}

0 commit comments

Comments
 (0)