broker.go 1.1 KB
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
}