-
Notifications
You must be signed in to change notification settings - Fork 1
/
wpc.go
78 lines (71 loc) · 1.67 KB
/
wpc.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
package wpc
import (
"github.com/apache/pulsar-client-go/pulsar"
"github.com/wshops/wpc/wpclogger"
"go.uber.org/zap"
"sync"
"time"
)
type wpc struct {
pulsarClient pulsar.Client
producerMap sync.Map
subscriberMap sync.Map
log *zap.SugaredLogger
}
var instance *wpc
func New(connectionUrl string, logger *zap.SugaredLogger, pulsarOptions ...*pulsar.ClientOptions) *wpc {
var c pulsar.Client
var err error
if len(pulsarOptions) == 0 {
c, err = pulsar.NewClient(pulsar.ClientOptions{
URL: connectionUrl,
OperationTimeout: 30 * time.Second,
ConnectionTimeout: 30 * time.Second,
Logger: wpclogger.NewBlackholeLogger(logger),
})
} else {
pulsarOptions[0].URL = connectionUrl
c, err = pulsar.NewClient(*pulsarOptions[0])
}
if err != nil {
logger.Error(err)
}
instance = &wpc{
pulsarClient: c,
log: logger,
}
return instance
}
func Close() {
if instance != nil {
instance.producerMap.Range(func(key, value interface{}) bool {
value.(pulsar.Producer).Close()
return true
})
instance.subscriberMap.Range(func(key, value interface{}) bool {
value.(*wpcSubscriber).Close()
return true
})
instance.pulsarClient.Close()
}
}
func (w *wpc) GetProducer(topic string) pulsar.Producer {
if producer, ok := w.producerMap.Load(topic); ok {
return producer.(pulsar.Producer)
}
p, err := w.pulsarClient.CreateProducer(pulsar.ProducerOptions{
Topic: topic,
})
if err != nil {
w.log.Error(err)
return nil
}
w.producerMap.Store(topic, p)
return p
}
func Pd(topic string) pulsar.Producer {
return instance.GetProducer(topic)
}
func (w *wpc) GetClient() pulsar.Client {
return w.pulsarClient
}