/
client.go
77 lines (62 loc) · 1.57 KB
/
client.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
package nsq
import (
"context"
"sync"
"github.com/JieTrancender/nsq_consumer/libconsumer/consumer"
"github.com/JieTrancender/nsq_consumer/libconsumer/logp"
"github.com/JieTrancender/nsq_consumer/libconsumer/outputs"
"github.com/nsqio/go-nsq"
)
type client struct {
logger *logp.Logger
outputs.NetworkClient
// for nsq
nsqd string
topic string
enabledTopic bool
producer *nsq.Producer
config *nsq.Config
mux sync.Mutex
}
func newNsqClient(config *Config) (*client, error) {
cfg := nsq.NewConfig()
cfg.WriteTimeout = config.WriteTimeout
cfg.DialTimeout = config.DialTimeout
c := &client{
logger: logp.NewLogger(logSelector),
nsqd: config.Nsqd,
topic: config.Topic,
config: cfg,
enabledTopic: config.EnabledTopic,
}
return c, nil
}
func (c *client) Close() error {
c.producer.Stop()
return nil
}
func (c *client) Connect() error {
c.mux.Lock()
defer c.mux.Unlock()
c.logger.Debugf("connect: %v", c.nsqd)
producer, err := nsq.NewProducer(c.nsqd, c.config)
if err != nil {
c.logger.Errorf("nsq connect fail with: %+v", err)
return err
}
// todo: set logger
c.producer = producer
return nil
}
func (c *client) Publish(_ context.Context, m consumer.Message) error {
if c.enabledTopic {
return c.producer.Publish(c.topic, m.GetMessageBody())
}
if m.GetNsqMessage().NSQDAddress == c.nsqd {
c.logger.Debugf("The nsq address are same as the message's address, maybe endless")
}
return c.producer.Publish(m.GetTopic(), m.GetMessageBody())
}
func (c *client) String() string {
return "NSQD"
}