broker.go
1.1 KB
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
package broker
import (
"fmt"
"github.com/linmadan/egglib-go/utils/json"
"github.com/zeromicro/go-queue/kq"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/log"
"strings"
"sync"
)
var defaultClientMap = make(map[string]*kq.Pusher)
var locker sync.RWMutex
type client struct {
pusher *kq.Pusher
}
func Register(host, topic string) *kq.Pusher {
if v, ok := defaultClientMap[topic]; ok {
return v
}
locker.Lock()
defer locker.Unlock()
pusher := kq.NewPusher(strings.Split(host, ","), topic)
defaultClientMap[topic] = pusher
return pusher
}
// Push 异步推送到队列
func Push(host string, topic string, o interface{}) error {
var pusher *kq.Pusher
if pusher = Register(host, topic); pusher == nil {
return fmt.Errorf("pusher client [%v] not found ", topic)
}
if err := pusher.Push(json.MarshalToString(o)); err != nil {
log.Logger.Debug(fmt.Sprintf("topic:%v error:%v", topic, err.Error()), map[string]interface{}{"message": o})
return err
} else {
log.Logger.Debug(fmt.Sprintf("topic:%v 发送成功", topic), map[string]interface{}{"message": o})
}
return nil
}