-
Notifications
You must be signed in to change notification settings - Fork 0
/
nats.go
63 lines (54 loc) · 1.21 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
53
54
55
56
57
58
59
60
61
62
63
package vcago
import (
"log"
"time"
"github.com/nats-io/nats.go"
)
// Nats represents the config struct for Nats service.
type NatsDAO struct {
url string
skip bool
connection *nats.EncodedConn
}
// Nats used for Nats connection
var Nats = new(NatsDAO)
func (i *NatsDAO) Connect() {
i.skip = Settings.Bool("NATS_SKIP", "n", false)
if i.skip {
return
}
i.url = Settings.String("NATS_URL", "w", "localhost")
nc, err := nats.Connect(i.url)
if err != nil {
log.Fatal(err, " ", "NatsUrl: ", i.url)
}
i.connection, err = nats.NewEncodedConn(nc, nats.JSON_ENCODER)
if err != nil {
log.Fatal(err)
}
log.Print("nats successfully connected!")
return
}
func (i *NatsDAO) Publish(message string, body interface{}) {
if i.skip {
return
}
i.connection.Publish(message, body)
}
func (i *NatsDAO) Subscribe(message string, catch interface{}) {
if i.skip {
return
}
_, err := i.connection.Subscribe(message, catch)
if err != nil {
//TODO: nats logging message
log.Print(err)
}
}
func (i *NatsDAO) Request(message string, request interface{}, response interface{}) (err error) {
if i.skip {
return
}
err = i.connection.Request(message, request, response, 1000*time.Millisecond)
return
}