-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
50 lines (45 loc) · 981 Bytes
/
main.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
package main
import (
"log"
"strconv"
"time"
nsq "github.com/nsqio/go-nsq"
)
func main() {
go startConsumer()
startProducer()
}
// 生产者
func startProducer() {
cfg := nsq.NewConfig()
producer, err := nsq.NewProducer("127.0.0.1:4150", cfg)
if err != nil {
log.Fatal(err)
}
// 发布消息
for {
i := time.Now().Unix()
if err := producer.Publish("test", []byte("test message - "+strconv.FormatInt(i, 10))); err != nil {
log.Fatal("publish error: " + err.Error())
}
time.Sleep(100 * time.Millisecond)
}
}
// 消费者
func startConsumer() {
cfg := nsq.NewConfig()
consumer, err := nsq.NewConsumer("test", "sensor01", cfg)
if err != nil {
log.Fatal(err)
}
// 设置消息处理函数
consumer.AddHandler(nsq.HandlerFunc(func(message *nsq.Message) error {
log.Println(string(message.Body))
return nil
}))
// 连接到单例nsqd
if err := consumer.ConnectToNSQD("127.0.0.1:4150"); err != nil {
log.Fatal(err)
}
<-consumer.StopChan
}