-
Notifications
You must be signed in to change notification settings - Fork 87
/
nsq_cons.go
51 lines (42 loc) · 1.06 KB
/
nsq_cons.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main
import (
"github.com/nsqio/go-nsq"
"log"
"os"
"os/signal"
"syscall"
)
// MyMessageHandler is a struct which defines a method to handle messages
type MyMessageHandler struct {
totalMessages int
}
// This is the message handler callback
func (h *MyMessageHandler) HandleMessage(message *nsq.Message) error {
h.totalMessages++
log.Printf("Message no %d received , body : %s \n", h.totalMessages, string(message.Body))
return nil
}
func main() {
// Create a consumer
config := nsq.NewConfig()
topicName := "my_topic"
channelName := "my_chan"
cons, err := nsq.NewConsumer(topicName, channelName, config)
if err != nil {
log.Fatal(err)
}
// Add the callback for messages
cons.AddHandler(&MyMessageHandler{})
// Connect to external NSQD
err = cons.ConnectToNSQD("127.0.0.1:4150")
if err != nil {
log.Panic("Could not connect to NSQD")
}
// Wait for a signal to quit
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
// Stop the consumer
cons.Stop()
<-cons.StopChan // wait for cleanup
}