This is a creation in Article, where the information may have evolved or changed.
NSQ is a real-time message queue written by bitly company using Golang.
NSQ official currently provides GOLANG,PY,JS client, this article briefly describes the use of Golang client writer.
The official Go client library is here: github.com/bitly/go-nsq
GO-NSQ provides a read-write interface for the upper layer, writer and reader, which means that if you want to send a message to NSQ, you first need to use writer, and if you want to read the message from NSQ, you need to create a reader.
Writer is relatively simple, the basic steps are as follows:
1, establish a connection with the NSQD server, establish writer
2. Use writer to send messages
The basic code is as follows:
Package Mainimport ("FMT" "github.com/bitly/go-nsq") Var (WR *nsq. Writer) func opennsq (Nsqaddr string) {if nsqaddr = = "" {nsqaddr = "127.0.0.1:4150"}WR = nsq. Newwriter (NSQADDR)}func clicks (UID, nid int64) {s: = FMT. Sprintf (' {' uid ':%d, ' nid ':%d} ', UID, nid) WR. Publish ("clicks", []byte (s))}
As you can see from the code above:
1, establish the connection using the Newwriter method, this method is very simple, only need to provide the server address.
2, writer uses the Publish method to send the message, the Publish method prototype is as follows:
Func (w *writer) Publish (topic string, Body []byte) (Int32, []byte, error)
The first parameter of publish is topic, and the second parameter is the content that needs to send the message. If you do not know what topic is, please refer to the Official document topic.
About Writer:
1, writer in the source code of GO-NSQD is a structure, not interface
2, Writer's publish method is synchronous send, writer also has Publishasync method, used to send messages asynchronously, and multipublish, synchronously send multiple messages, Multipublishasync, asynchronously send multiple messages;
3. When the writer is finished, the writer should be closed by using the Stop method.