forked from pibigstar/go-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnsq.go
117 lines (100 loc) · 2.27 KB
/
nsq.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package nsq
import (
"flag"
"fmt"
"sync"
"time"
"github.com/youzan/go-nsq"
)
func init() {
flag.StringVar(&env, "env", "dev", "the nsq environment")
}
type (
Message = nsq.Message
)
type Config struct {
config *nsq.Config
lookAddr string
}
var (
env string
pubMu = &sync.RWMutex{}
pubMgrs = make(map[string]*nsq.TopicProducerMgr)
consumers = &sync.Map{}
)
var DefaultConfig = func() *Config {
cfg := nsq.NewConfig()
return &Config{
config: cfg,
lookAddr: "127.0.0.1:4161",
}
}()
func getPubMgr(topic string) (*nsq.TopicProducerMgr, error) {
pubMu.RLock()
if pubMgr, ok := pubMgrs[topic]; ok {
pubMu.RUnlock()
return pubMgr, nil
}
pubMu.RUnlock()
pubMu.Lock()
defer pubMu.Unlock()
pubMgr, err := nsq.NewTopicProducerMgr([]string{topic}, DefaultConfig.config)
if err != nil {
return nil, err
}
err = pubMgr.ConnectToNSQLookupd(DefaultConfig.lookAddr)
if err != nil {
return nil, err
}
pubMgrs[topic] = pubMgr
return pubMgr, nil
}
func wrapTopic(topic string) string {
return fmt.Sprintf("%s-%s", topic, env)
}
func Publish(topic string, data []byte) error {
topic = wrapTopic(topic)
pubMgr, err := getPubMgr(topic)
if err != nil {
return err
}
return pubMgr.Publish(topic, data)
}
func Consume(topic, channel string, handlerFunc nsq.HandlerFunc, concurrency int) error {
topic = wrapTopic(topic)
consumer, err := nsq.NewConsumer(topic, channel, DefaultConfig.config)
if err != nil {
return err
}
consumer.AddConcurrentHandlers(handlerFunc, concurrency)
// set the consumer to map for close
key := topic + ":" + channel
consumers.Store(key, consumer)
return consumer.ConnectToNSQLookupd(DefaultConfig.lookAddr)
}
func Close() {
// 记录关闭过得mgr,每个pubMgr仅可被关闭一次
closedPubMgrs := &sync.Map{}
pubMu.RLock()
for _, pubMgr := range pubMgrs {
if _, ok := closedPubMgrs.Load(pubMgr); ok {
continue
}
closedPubMgrs.Store(pubMgr, struct{}{})
pubMgr.Stop()
}
pubMu.RUnlock()
// close the consumer
consumers.Range(func(key, value interface{}) bool {
if consumer, ok := value.(*nsq.Consumer); ok {
consumer.Stop()
select {
case <-consumer.StopChan:
case <-time.After(time.Second * 60):
//等待一分钟让其关闭handler
}
}
consumers.Delete(key)
return true
})
}