-
Notifications
You must be signed in to change notification settings - Fork 1
/
producer.go
95 lines (76 loc) · 1.85 KB
/
producer.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package que
import (
"encoding/json"
"math/rand"
"strconv"
"sync"
"github.com/jcoene/env"
"github.com/nsqio/go-nsq"
)
var ppool []*nsq.Producer
var pcount int
var ponce sync.Once
func Publish(topic string, v interface{}) (err error) {
var p *nsq.Producer
var buf []byte
if buf, err = json.Marshal(v); err != nil {
return
}
if p, err = getProducer(); err != nil {
return err
}
return p.Publish(topic, buf)
}
func PublishBytes(topic string, buf []byte) error {
p, err := getProducer()
if err != nil {
return err
}
return p.Publish(topic, buf)
}
func MultiPublish(topic string, vs ...interface{}) (err error) {
var p *nsq.Producer
body := make([][]byte, 0)
for _, v := range vs {
var buf []byte
if buf, err = json.Marshal(v); err != nil {
return
}
body = append(body, buf)
}
if p, err = getProducer(); err != nil {
return err
}
return p.MultiPublish(topic, body)
}
func getProducer() (*nsq.Producer, error) {
// Performed once to set up the slice of nsq.Producer
ponce.Do(setupProducers)
// Choose a random connection from the pool
return ppool[rand.Intn(pcount)], nil
}
// Performed only once the first time a producer is needed. Sets up a slice of
// nsq.Producer which will be used round-robin.
func setupProducers() {
// Create an empty pool of producers
ppool = make([]*nsq.Producer, 0)
// Determine how many producers with the NSQD_POOL environment variable.
// Defaults to 1
pcount = 1
if env.Get("NSQD_POOL") != "" {
num, err := strconv.Atoi(env.Get("NSQD_POOL"))
if err == nil && num > 0 {
pcount = num
}
}
// Get the nsqd host (you can use haproxy if > 1 pool connection)
host := env.GetOr("NSQD_HOST", "127.0.0.1:4150")
// Fill the pool with connections
for i := 0; i < pcount; i++ {
p, err := nsq.NewProducer(host, nsq.NewConfig())
if err != nil {
panic(err)
}
ppool = append(ppool, p)
}
}