package main
import (
"context"
"fmt"
ratelimit2 "github.com/juju/ratelimit"
"github.com/micro/go-micro"
"github.com/micro/go-micro/broker"
"github.com/micro/go-micro/config"
"github.com/micro/go-micro/config/source/file"
"github.com/micro/go-micro/registry"
etcd2 "github.com/micro/go-micro/registry/etcd"
"github.com/micro/go-micro/transport/grpc"
"github.com/micro/go-plugins/wrapper/ratelimiter/ratelimit"
pb "micro.study.zozoo.net/proto"
"time"
)
type Hello struct {}
func (c *Hello)Info(ctx context.Context,res *pb.Request,resp *pb.Response) error {
resp.Name = res.Name
resp.Id = 1
resp.Score = 100
return nil
}
type Cfg struct {
Name string
Etcd struct{
Address []string
}
}
func main() {
// 加载配置文件
if err := config.Load(file.NewSource(
file.WithPath("./config/config.json"),
)); err != nil {
fmt.Println(err)
return
}
var cfg Cfg
if err := config.Get().Scan(&cfg); err != nil {
fmt.Println(err)
return
}
//还可以这样获取里面的子配置
//if err := config.Get("hosts", "database").Scan(&cfg); err != nil {
// fmt.Println(err)
// return
//}
fmt.Println(cfg.Etcd,cfg.Name)
etcd := etcd2.NewRegistry(func(options *registry.Options) {
options.Addrs = cfg.Etcd.Address//使用配置
})
//限流
limit := 1
c := ratelimit2.NewBucketWithRate(float64(limit),int64(limit))
//lb := ratelimiter.NewLeakyBucket(limit,1*time.Second)
//创建服务
server := micro.NewService(
micro.Name(cfg.Name),//使用配置
micro.Registry(etcd),
micro.Transport(grpc.NewTransport()),
micro.WrapHandler(ratelimit.NewHandlerWrapper(c,true)),
)
//初始化
server.Init()
//broker初始化
if err := broker.Init();err != nil{
panic(err.Error())
}
if err := broker.Connect();err != nil {
panic(err.Error())
}
//异步调用broker的发布与订阅
go publish()
go subscribe()
//注册方法
pb.RegisterHelloHandler(server.Server(),new(Hello))
if err := server.Run(); err != nil {
fmt.Println(err)
}
}
var topic = "rabbitMq"
//消息发布
func publish(){
t := time.NewTicker(time.Second)
for times := range t.C {
err := broker.Publish(topic,&broker.Message{
Header:map[string]string{
"name":"gangan",
"age":"19",
},
Body:[]byte(times.String()),
})
if err != nil {
panic(err.Error())
}
}
}
//消息订阅
func subscribe() {
_, err := broker.Subscribe(topic, func(event broker.Event) error {
b := event.Message().Body
fmt.Println(string(b))
h := event.Message().Header
fmt.Println(h)
return nil
})
if err != nil {
panic(err.Error())
}
}
go-micro broker的发布与订阅
最新推荐文章于 2022-05-07 13:11:06 发布