-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnats.go
52 lines (46 loc) · 1.23 KB
/
nats.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package bop
import (
"log"
"os"
"time"
"github.com/nats-io/nats"
)
// NewConnection creates a new nats encoded connection, If reconnect is true,
// the connection will attempt ot repair itself on disconnect
func NewConnection(reconnect bool) *nats.EncodedConn {
var address string
if host := os.Getenv("NATS_HOST"); host == "" {
address = nats.DefaultURL
} else {
address = host
}
options := []nats.Option{
nats.MaxReconnects(10),
nats.ReconnectWait(2 * time.Second),
nats.DisconnectHandler(func(_ *nats.Conn) {
log.Print("Got disconnected!\n")
}),
nats.ReconnectHandler(func(nc *nats.Conn) {
log.Printf("Got reconnected to %v!\n", nc.ConnectedUrl())
}),
nats.ClosedHandler(func(nc *nats.Conn) {
log.Printf("Connection closed. Reason: %q\n", nc.LastError())
}),
}
var c *nats.Conn
var err error
switch reconnect {
case true:
c, err = nats.Connect(address, options...)
case false:
c, err = nats.Connect(address)
}
if err != nil {
log.Fatalf("Error trying to connect to nats server at %q, got error: %q", address, err)
}
nc, err := nats.NewEncodedConn(c, nats.GOB_ENCODER)
if err != nil {
log.Fatalf("Error trying to connect to encoded connection at %q, got error: %q", address, err)
}
return nc
}