消息订阅
接口除了同步调用,还可以使用消息队列进行异步的调用,micro为我们提供良好的pub/sub订阅通知服务,上一篇文章中,使用了micro提供的示例代码,这节继续使用示例代码中的例子
//其他代码省略
// 注册一个消息服务,已struct的方式注册
micro.RegisterSubscriber("com.foo.srv.hello", service.Server(), new(subscriber.Example),
server.SubscriberQueue("queue_hello_struct"))
// 注册一个消息服务,已function的方式注册
micro.RegisterSubscriber("com.foo.srv.hello", service.Server(), subscriber.Handler,
server.SubscriberQueue("queue_function_struct"))
Function是指接收一次请求
启动服务
go run main.go --registry=etcd --registry_address=http://127.0.0.1:2379
订阅服务已经启动,接下来是需要编写客户端的脚本
//创建一个客户端
service:=micro.NewService(
micro.Name("com.foo.srv.client"),
)
//初始化
service.Init()
//定义客户端
publish := micro.NewPublisher("com.foo.srv.hello",service.Client())
//发送消息
for i := 0 ;i<= 1000;i++ {
publish.Publish(context.Background(),example.Message{
Say:"hello,xiaobaijun"+strconv.Itoa(i),
},client.WithExchange("queue_hello_struct"))
}
启动服务
go run main.go --registry=etcd --registry_address=http://127.0.0.1:2379
使用micro我们构建了一个简单的Pub/Sub服务
包装器
现在需要对所有服务的请求都进行打印日志的处理,可以使用包装器,相当于gin框架的中间件处理
service := micro.NewService(
micro.Name("com.foo.srv.order"),
micro.Version("latest"),
micro.Registry(etcd.NewRegistry(func(op *registry.Options) {
op.Addrs = []string{"192.168.99.100:2379"}
})),
//使用限流的方式
micro.WrapHandler(func(handlerFunc server.HandlerFunc) server.HandlerFunc {
return func(ctx context.Context, req server.Request, rsp interface{}) error {
fmt.Printf("[%v] server request: %s", time.Now(), req.Endpoint())
return handlerFunc(ctx, req, rsp)
}
}),
)
使用包装器,可以完全限流,鉴权等操作处理