broker.go 1.2 KB
package broker

import (
	"fmt"
	"github.com/linmadan/egglib-go/utils/json"
	"github.com/tal-tech/go-queue/kq"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/constant"
	"strings"
)

var defaultClientMap = make(map[string]*kq.Pusher)

type client struct {
	pusher *kq.Pusher
}

func RegisterDefaultPusherClient(host, topic string) {
	if _, ok := defaultClientMap[topic]; ok {
		panic("duplicate register pusher client")
	}
	pusher := kq.NewPusher(strings.Split(host, ","), topic)
	defaultClientMap[topic] = pusher
}

// 异步推送到队列
func Push(topic string, o interface{}) error {
	if !constant.EnableBlockChain {
		return nil
	}
	var pusher *kq.Pusher
	var ok bool
	if pusher, ok = defaultClientMap[topic]; !ok {
		return fmt.Errorf("pusher client [%v] not found ", topic)
	}
	return pusher.Push(json.MarshalToString(o))
}

// 新建一个推送对象
func NewPushObject(source, primaryId, issueId string, obj interface{}) interface{} {
	data := map[string]interface{}{
		"source":    source,
		"primaryId": primaryId,
		"issueId":   issueId,
		"data":      json.MarshalToString(obj),
	}
	return map[string]interface{}{
		"topic": "up_block_chain",
		"data":  data,
	}
}