From ce3a7074321c1cb6fd4073992a193f2e5d1c45c9 Mon Sep 17 00:00:00 2001 From: Pierce Lopez Date: Fri, 14 Aug 2020 15:22:04 -0400 Subject: [PATCH] docs: add exit-on-signal and more comments to example consumer --- doc.go | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/doc.go b/doc.go index 589e641c..85cc30c6 100644 --- a/doc.go +++ b/doc.go @@ -8,15 +8,24 @@ Consumer Consuming messages from NSQ can be done by creating an instance of a Consumer and supplying it a handler. + package main + import ( + "log" + "os/signal" + "github.com/nsqio/go-nsq" + ) + type myMessageHandler struct {} // HandleMessage implements the Handler interface. func (h *myMessageHandler) HandleMessage(m *nsq.Message) error { if len(m.Body) == 0 { // Returning nil will automatically send a FIN command to NSQ to mark the message as processed. + // In this case, a message with an empty body is simply ignored/discarded. return nil } + // do whatever actual message processing is desired err := processMessage(m.Body) // Returning a non-nil error will automatically send a REQ command to NSQ to re-queue the message. @@ -42,6 +51,11 @@ Consuming messages from NSQ can be done by creating an instance of a Consumer an log.Fatal(err) } + // wait for signal to exit + sigChan := make(chan os.Signal, 1) + signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) + <-sigChan + // Gracefully stop the consumer. consumer.Stop() } @@ -67,7 +81,7 @@ Producing messages can be done by creating an instance of a Producer. log.Fatal(err) } - // Gracefully stop the producer. + // Gracefully stop the producer when appropriate (e.g. before shutting down the service) producer.Stop() */