1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-12-12 08:23:58 +02:00
go-micro/examples/pubsub/main.go

60 lines
1.1 KiB
Go
Raw Normal View History

2015-04-26 21:45:46 +02:00
package main
import (
"fmt"
"time"
2015-05-23 18:55:08 +02:00
log "github.com/golang/glog"
2015-11-20 18:17:33 +02:00
"github.com/micro/go-micro/broker"
"github.com/micro/go-micro/cmd"
2015-04-26 21:45:46 +02:00
)
var (
topic = "go.micro.topic.foo"
)
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())),
}
if err := broker.Publish(topic, msg); err != nil {
2015-05-23 18:55:08 +02:00
log.Errorf("[pub] failed: %v", err)
} else {
fmt.Println("[pub] pubbed message:", string(msg.Body))
2015-05-23 18:55:08 +02:00
}
2015-04-26 21:45:46 +02:00
i++
}
}
func sub() {
2015-12-23 21:16:55 +02:00
_, err := broker.Subscribe(topic, func(p broker.Publication) error {
fmt.Println("[sub] received message:", string(p.Message().Body), "header", p.Message().Header)
return nil
2015-04-26 21:45:46 +02:00
})
if err != nil {
fmt.Println(err)
}
}
func main() {
2015-05-23 18:55:08 +02:00
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)
}
2015-04-26 21:45:46 +02:00
go pub()
go sub()
<-time.After(time.Second * 10)
}