This repository was archived by the owner on Dec 2, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.go
More file actions
64 lines (49 loc) · 1.33 KB
/
queue.go
File metadata and controls
64 lines (49 loc) · 1.33 KB
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
64
package main
import (
"math"
"time"
nats "github.com/nats-io/go-nats"
log "github.com/sirupsen/logrus"
)
// SubscribeToQueue sets up a subscription in NATS on the "pipelines" subject.
// TODO: abstract away the dependency on NATS.
func SubscribeToQueue(url, subject, group string) (<-chan *nats.Msg, func()) {
logger.Info("connecting to nats")
nc, err := nats.Connect(url)
if err != nil {
for i := 1; i <= 3; i++ {
timeout := time.Duration(math.Pow(2, float64(i))) * time.Second
logger.WithFields(log.Fields{
"error": err,
}).Warnf("error connecting to nats, retrying after %v seconds", timeout)
time.Sleep(timeout)
nc, err = nats.Connect(url)
if err == nil {
break
}
}
}
logger.Info("nats connection successful")
ch := make(chan *nats.Msg)
sub, err := nc.ChanQueueSubscribe(subject, group, ch)
if err != nil {
logger.Fatalf("error listening to subject %v: %v", subject, err)
}
logger = logger.WithFields(log.Fields{
"subject": subject,
"group": group,
})
logger.Debug("queue group joined")
teardown := func() {
logger.Debugf("begin tearing down nats connection")
defer nc.Close()
err := sub.Unsubscribe()
if err != nil {
logger.WithFields(log.Fields{
"error": err,
}).Fatalf("unable to cleanly unsubscribe from subject %v", subject)
}
close(ch)
}
return ch, teardown
}