github.com/sereiner/library@v0.0.0-20200518095232-1fa3e640cc5f/mq/nsq/nsq.producer.go (about) 1 package nsq 2 3 import ( 4 "errors" 5 "time" 6 7 "github.com/nsqio/go-nsq" 8 logger "github.com/sereiner/library/log" 9 "github.com/sereiner/library/mq" 10 ) 11 12 //NsqProducer Producer 13 type NsqProducer struct { 14 address string 15 client *nsq.Producer 16 backupMsg chan *mq.ProcuderMessage 17 closeCh chan struct{} 18 done bool 19 *mq.OptionConf 20 } 21 22 func NewNsqProducer(address string, opts ...mq.Option) (producer *NsqProducer, err error) { 23 producer = &NsqProducer{address: address} 24 producer.OptionConf = &mq.OptionConf{ 25 Logger: logger.GetSession("mq.nsq", logger.CreateSession()), 26 } 27 producer.closeCh = make(chan struct{}) 28 for _, opt := range opts { 29 opt(producer.OptionConf) 30 } 31 return 32 } 33 34 //Connect 循环连接服务器 35 func (producer *NsqProducer) Connect() (err error) { 36 producer.client, err = nsq.NewProducer(producer.address, nsq.NewConfig()) 37 if err != nil { 38 return err 39 } 40 41 return producer.client.Ping() 42 } 43 44 //GetBackupMessage 获取备份数据 45 func (producer *NsqProducer) GetBackupMessage() chan *mq.ProcuderMessage { 46 return producer.backupMsg 47 } 48 49 //Send 发送消息 50 func (producer *NsqProducer) Send(queue string, msg string, timeout time.Duration) (err error) { 51 if producer.done { 52 return errors.New("mq producer 已关闭") 53 } 54 55 return producer.client.Publish(queue, []byte(msg)) 56 } 57 58 //Close 关闭当前连接 59 func (producer *NsqProducer) Close() { 60 producer.done = true 61 close(producer.closeCh) 62 close(producer.backupMsg) 63 producer.client.Stop() 64 } 65 66 type nsqProducerResolver struct { 67 } 68 69 func (s *nsqProducerResolver) Resolve(address string, opts ...mq.Option) (mq.MQProducer, error) { 70 return NewNsqProducer(address, opts...) 71 } 72 73 func init() { 74 mq.RegisterProducer("nsq", &nsqProducerResolver{}) 75 }