Go-NSQ is the official Go client for NSQ. It's available at https://github.com/nsqio/go-nsq.
Here is the NewProducer function:
func NewProducer(addr string, config *Config) (*Producer, error)
It returns an instance of Producer for the specified nsqd address. There is a one-to-one mapping between an nsqd instance and a client Producer instance. The TCP connection is managed in a lazy manner (the connect will happen when publish is done).
Configuration contains a bunch of tuneables and is created through the NewConfig() method.
The Producer struct has two methods for publishing messages:
- Synchronous publish:
func (w *Producer) Publish(topic string, body []byte) error
- Asynchronous publish:
func (w *Producer) PublishAsync(topic string, body []byte, doneChan chan *ProducerTransaction, args...interface{}) error
This method sends the message asynchronously and returns instantly after calling. The doneChan channel gets an instance of ProducerTransaction with the args that were supplied and errors if there are any. The args are used mostly for housekeeping purposes.
The following code snippet demonstrates publishing a message:
package main import ( "fmt" "github.com/nsqio/go-nsq" "log" ) func main() { // Connect pCfg := nsq.NewConfig() producer, err := nsq.NewProducer("127.0.0.1:4160", pCfg) if err != nil { log.Fatalf("failed creating producer %s", err) } // Publish Async destinationTopic := "my_topic" responseChan := make(chan *ProducerTransaction) err = producer.PublishAsync(destinationTopic, []byte("a_message"), responseChan, "some_args") // Check for status // Done here inline just for showcase status := <-responseChan if status.Error != nil { log.Printf("Error received %s ", status.Error.Error()) } else { log.Printf("Success Arg received : %s ", status.Args[0].(string)) // should be some_args } }