/
nsq-test.go
126 lines (104 loc) · 2.57 KB
/
nsq-test.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package main
import (
"bytes"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/bitly/go-nsq"
"github.com/joshuarubin/chanpubsub"
)
const (
numModules = 10
lookupd = "127.0.0.1:4161" // this addr is OK to hardcode
nsqd = "127.0.0.1:4150" // this addr is OK to hardcode
nsqhttpd = "127.0.0.1:4151" // this addr is OK to hardcode
nsqChan = "worker"
)
type msgHandler struct {
ID int
SigPub *chanpubsub.ChanPubSub
}
func (h *msgHandler) HandleMessage(message *nsq.Message) error {
if h.ID+1 < numModules {
var bodyBuf bytes.Buffer
bodyBuf.Write(message.Body)
fmt.Fprintf(&bodyBuf, "processed by mod%d\n", h.ID)
topic := fmt.Sprintf("mod%d", h.ID+1)
//log.Printf("publishing to topic %s\n", topic)
if _, _, err := nsq.NewWriter(nsqd).Publish(topic, bodyBuf.Bytes()); err != nil {
log.Println(err)
return err
}
} else if h.ID+1 == numModules {
log.Printf("received on mod%d\n%s\n", h.ID, message.Body)
h.SigPub.Pub(struct{}{})
}
return nil
}
func module(moduleID int, ps *chanpubsub.ChanPubSub, termChan <-chan interface{}, exitChan chan<- struct{}) {
topic := fmt.Sprintf("mod%d", moduleID)
createTopic(topic)
go func() {
//log.Printf("topic: %s, channel: %s\n", topic, nsqChan)
reader, err := nsq.NewReader(topic, nsqChan)
if err != nil {
log.Fatalln(err)
}
reader.VerboseLogging = false
reader.LookupdPollInterval = 15 * time.Second
reader.AddHandler(&msgHandler{
ID: moduleID,
SigPub: ps,
})
err = reader.ConnectToLookupd(lookupd)
if err != nil {
log.Fatalln(err)
}
for {
select {
case <-reader.ExitChan:
exitChan <- struct{}{}
return
case <-termChan:
//log.Printf("module %d received signal\n", moduleID)
reader.Stop()
}
}
}()
}
func sigHandler() *chanpubsub.ChanPubSub {
termChan := make(chan os.Signal, 1)
signal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
ps := chanpubsub.New()
go func() {
ps.Pub(<-termChan)
return
}()
return ps
}
func createTopic(topic string) {
if _, err := http.Get("http://" + nsqhttpd + "/create_topic?topic=" + topic); err != nil {
log.Fatal(err)
}
}
func main() {
ps := sigHandler()
exitChan := make(chan struct{})
for i := 0; i < numModules; i++ {
moduleID := i // get a loop local counter
termChan, _ := ps.Sub()
module(moduleID, ps, termChan, exitChan)
}
if _, _, err := nsq.NewWriter(nsqd).Publish("mod0", []byte("sent\n")); err != nil {
log.Fatalln(err)
}
//log.Println("message sent")
for i := 0; i < numModules; i++ {
<-exitChan
//log.Println("module exit", i)
}
}