github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/data/queue/producer/nsq.go (about) 1 package producer 2 3 import ( 4 "fmt" 5 "github.com/angenalZZZ/gofunc/log" 6 json "github.com/json-iterator/go" 7 "github.com/nsqio/go-nsq" 8 "github.com/rs/zerolog" 9 "runtime" 10 ) 11 12 type NsqProducer struct { 13 Log *log.Logger 14 *nsq.Producer 15 } 16 17 // NewNsqProducer create a nsq producer. 18 func NewNsqProducer(addr string, config ...*nsq.Config) (p *NsqProducer, err error) { 19 var ( 20 l *log.Logger 21 ll zerolog.Level 22 np *nsq.Producer 23 cf *nsq.Config 24 ) 25 26 if log.Log != nil { 27 l = log.Log 28 } else { 29 l = log.InitConsole("2006-01-02 15:04:05.000", false) 30 ll = zerolog.ErrorLevel 31 l.Level(ll) 32 } 33 34 if len(config) > 0 { 35 cf = config[0] 36 } else { 37 cf = nsq.NewConfig() 38 } 39 40 np, err = nsq.NewProducer(addr, cf) 41 if err != nil { 42 return 43 } 44 45 np.SetLogger(p, nsq.LogLevel(int(ll))) 46 p = &NsqProducer{ 47 Log: l, 48 Producer: np, 49 } 50 return 51 } 52 53 // PublishJSONAsync sends message to nsq topic in json format asynchronously. 54 func (p *NsqProducer) PublishJSONAsync(topic string, v interface{}, doneChan chan *nsq.ProducerTransaction, 55 args ...interface{}) error { 56 body, err := json.ConfigCompatibleWithStandardLibrary.Marshal(v) 57 if err != nil { 58 return err 59 } 60 return p.Producer.PublishAsync(topic, body, doneChan, args...) 61 } 62 63 // PublishJSON sends message to nsq topic in json format. 64 func (p *NsqProducer) PublishJSON(topic string, v interface{}) error { 65 body, err := json.ConfigCompatibleWithStandardLibrary.Marshal(v) 66 if err != nil { 67 return err 68 } 69 return p.Producer.Publish(topic, body) 70 } 71 72 // Output log. 73 func (p *NsqProducer) Output(calldepth int, s string) error { 74 if p.Log.GetLevel() == zerolog.DebugLevel { 75 _, file, line, ok := runtime.Caller(calldepth) 76 if !ok { 77 file = "???" 78 line = 0 79 } 80 s = fmt.Sprintf("%s %04d: %s", file, line, s) 81 } 82 p.Log.Print(s) 83 return nil 84 }