This is a creation in Article, where the information may have evolved or changed.
The previous article briefly introduced the use of the NSQ writer section: http://guotie.sinaapp.com/?p=533, this article describes the use of reader.
Similar to writer, NSQ provides a high-level interface: Reader. However, the reader section also needs to provide a handler to handle the received messages.
NSQ Reader's handler is an interface that is defined as follows:
Type Handler Interface { handlemessage (message *message) Error}
The main thing we do is to implement this interface.
The basic steps of reader are as follows:
1, a new NSQ reader;
Newreader is defined as follows:
Func newreader (topic string, Channel String) (*reader, error)
Topic is NSQD's Topic,channel can be understood as the name of this reader. A topic can have multiple readers at the same time, and each reader is a channel.
2, the use of AddHandler will specifically deal with the message Handler added to reader;
In addition to the AddHandler function, there is also Addsynchandler, which adds a function to the asynchronous processing of the message to reader, which can refer to the document for more information.
3, reader connection nsqd;
When reader connects to NSQD, GO-NSQ receives the message and calls our handler to process the message.
Package Nsqexampleimport ("github.com/bitly/go-nsq" " fmt") var _ = Fmt. Printfvar (rd *NSQ. Reader) type ClickHandler struct {nsqaddr string}func nsqclick (nsqaddr string) {rd, err: = nsq. Newreader ("clicks", "CH1") if err! = Nil {panic (err. Error ())}click: = Clickhandler{nsqaddr:nsqaddr}rd. AddHandler (&click) Err = Rd. CONNECTTONSQ (CLICK.NSQADDR) if err! = Nil {panic (err. Error ())}}func (c *clickhandler) handlemessage (msg *nsq. Message) Error { //Processing message code FMT. Println (String (Msg. Body)) return nil}
GO-NSQ's Official document: Http://godoc.org/github.com/bitly/go-nsq#Reader