This is a creation in Article, where the information may have evolved or changed.
NSQ Golang client Simple to use
NSQ is a Message Queuing system developed by a foreign short-chain service provider, bitly, using Golang, just to use this thing, which is simply recorded here.
Get Client
NSQ's Golang client is the official version of the
go get github.com/nsqio/go-nsq
Can
Simple Consumer and producer use
The client has the original command function for some basic operations, as well as consumer and producer encapsulation, which I am using directly in the encapsulation.
The consumer is relatively simple, as long as listening to queue messages, and processing on it, here is a simple example.
type NSQHandler struct {}func (this *NSQHandler) HandleMessage(message *nsq.Message) error { log.Println("recv:", string(message.Body)) return nil}func testNSQ() { waiter := sync.WaitGroup{} waiter.Add(1) go func() { defer waiter.Done() consumer, err := nsq.NewConsumer("test", "ch1", nsq.NewConfig()) if nil != err { log.Println(err) return } consumer.AddHandler(&NSQHandler{}) err = consumer.ConnectToNSQD("10.100.156.207:4150") if nil != err { log.Println(err) return } select {} }() waiter.Wait()}
Once the consumer is created, you only need to create a struct and implement the Handlemessage method, and then process the message when there is a message.
It is important to note that AddHandler callbacks are performed in other routine, and multiple handler can be added for processing messages, which may require attention to the synchronization of the thread.
Producers, like consumers, first need to create a producer
func (this *MsgQueue) Init(addr string) error { var err error this.addr = addr // try to connect cfg := nsq.NewConfig() this.producer, err = nsq.NewProducer(addr, cfg) if nil != err { return err } // try to ping err = this.producer.Ping() if nil != err { this.producer.Stop() this.producer = nil return err } return nil}
Producer encapsulates a number of methods, which can be divided into two types: synchronous and asynchronous. With the async suffix, it is asynchronous.
Synchronization is a function that is returned after the NSQ response is received, so it may be blocked and asynchronous, and the caller needs to pass in a Chan to receive the result, and when the result returns or is timed out, the corresponding content is written to the Chan.
Here I use the synchronous API, after all, if the message queue what the problem, then the entire service is not available, and synchronous asynchronous is not too cumbersome, can be modified later.
The Publish method is also very simple, providing a topic and data on the line.