forked from crosbymichael/hooks
/
util.go
67 lines (59 loc) · 1.36 KB
/
util.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
64
65
66
67
package main
import (
"os"
"os/signal"
"syscall"
"time"
"github.com/bitly/go-nsq"
"github.com/dancannon/gorethink"
)
type QueueOpts struct {
LookupdAddr string
Topic string
Channel string
Concurrent int
Signals []os.Signal
}
func QueueOptsFromContext(topic, channel string) QueueOpts {
return QueueOpts{
Signals: []os.Signal{syscall.SIGTERM, syscall.SIGINT},
LookupdAddr: config.Lookupd,
Topic: topic,
Channel: channel,
Concurrent: 1,
}
}
func ProcessQueue(handler nsq.Handler, opts QueueOpts) error {
if opts.Concurrent == 0 {
opts.Concurrent = 1
}
s := make(chan os.Signal, 64)
signal.Notify(s, opts.Signals...)
consumer, err := nsq.NewConsumer(opts.Topic, opts.Channel, nsq.NewConfig())
if err != nil {
return err
}
consumer.AddConcurrentHandlers(handler, opts.Concurrent)
if err := consumer.ConnectToNSQLookupd(opts.LookupdAddr); err != nil {
return err
}
for {
select {
case <-consumer.StopChan:
return nil
case sig := <-s:
logger.WithField("signal", sig).Debug("received signal")
consumer.Stop()
}
}
return nil
}
func NewRethinkdbSession() (*gorethink.Session, error) {
return gorethink.Connect(gorethink.ConnectOpts{
Database: config.RethinkdbDatabase,
AuthKey: config.RethinkdbKey,
Address: config.RethinkdbAddress,
MaxIdle: 10,
IdleTimeout: 20 * time.Second,
})
}