forked from real-jacket/tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
64 lines (56 loc) · 1.33 KB
/
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main
import (
"fmt"
"time"
"github.com/micro/go-micro/broker"
"github.com/micro/go-micro/config/cmd"
"github.com/micro/go-micro/util/log"
)
var (
topic = "go.micro.learning.topic.log"
b broker.Broker
)
func pub() {
tick := time.NewTicker(time.Second)
i := 0
for range tick.C {
msg := &broker.Message{
Header: map[string]string{
"id": fmt.Sprintf("%d", i),
},
Body: []byte(fmt.Sprintf("%d: %s", i, time.Now().String())),
}
log.Infof(broker.String())
if err := broker.Publish(topic, msg); err != nil {
log.Infof("[pub] Message publication failed: %v", err)
} else {
fmt.Println("[pub] Message published: ", string(msg.Body))
}
i++
}
}
func sub() {
_, err := broker.Subscribe(topic, func(p broker.Event) error {
log.Infof("[sub] Received Body: %s, Header: %s\n", string(p.Message().Body), p.Message().Header)
return nil
})
if err != nil {
fmt.Println(err)
}
}
func main() {
// cmd.Init() parses flags and env variables.
// If you leave out cmd.Init(),
// broker "http" will be used as default
// other than ones like nats you have specified.
cmd.Init()
if err := broker.Init(); err != nil {
log.Fatalf("broker.Init() error: %v", err)
}
if err := broker.Connect(); err != nil {
log.Fatalf("broker.Connect() error: %v", err)
}
go pub()
go sub()
<-time.After(time.Second * 20)
}