package main // This is a basic example of running an nsqd instance embedded. It creates // and runs an nsqd with all of the default options, and then produces // and consumes a single message. // See https://github.com/bitly/nsq/blob/master/nsqd/options.go and // https://github.com/bitly/nsq/blob/master/apps/nsqd/nsqd.go for // more details on how to configure an embedded nsqd instance. import ( "bytes" "log" "os" "os/signal" "syscall" "time" "github.com/bitly/go-nsq" "github.com/bitly/nsq/nsqd" ) func runDefaultNSQD() { signalChan := make(chan os.Signal, 1) signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM) opts := nsqd.NewNSQDOptions() nsqd := nsqd.NewNSQD(opts) nsqd.Main() <-signalChan nsqd.Exit() } func main() { // Run the embedded nsqd in a go routine go runDefaultNSQD() cfg := nsq.NewConfig() // the message we'll send to ourselves msg := []byte("the message") // Set up a Producer, pointing at the default host:port p, err := nsq.NewProducer("localhost:4150", cfg) if err != nil { log.Fatal(err) } // Publish a single message to the 'embedded' topic err = p.Publish("embedded", msg) //[]byte("one message")) if err != nil { log.Fatal(err) } // Now set up a consumer c, err := nsq.NewConsumer("embedded", "local", cfg) if err != nil { log.Fatal(err) } // and a single handler that just checks that the message we // received matches the message we sent c.AddHandler(nsq.HandlerFunc(func(m *nsq.Message) error { if bytes.Compare(m.Body, msg) != 0 { //"one message" { log.Fatal("message didn't match:", string(m.Body)) } else { log.Println("message matched:", string(m.Body)) } return nil })) // Connect the consumer to the embedded nsqd instance c.ConnectToNSQD("localhost:4150") // Sleep a little to give everything time to start up and let // our producer and consumer run time.Sleep(250 * time.Millisecond) }