包装器
包装器#
前言:包装器是 Go Micro 的中间件
概述#
包装器是 Go Micro 的中间件。我们希望创建一个可扩展的框架,其中包含钩子,以添加非核心要求的额外功能。很多时候,你需要执行的东西,如验证,跟踪等,所以这提供了这样做的能力.
为此我们使用了 “修饰器模式”.
使用#
这里有一些示例用法和真实代码 examples/wrapper.
你可以在这里 go-plugins/wrapper 中找到一系列的包装器.
处理器#
下面是一个示例服务处理程序包装器,它记录传入的请求
// 实现 server.HandlerWrapper
func logWrapper(fn 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 fn(ctx, req, rsp)
}
}
创建服务时可以初始化
service := micro.NewService(
micro.Name("greeter"),
// wrap the handler
micro.WrapHandler(logWrapper),
)
客户端#
下面是客户端包装器的示例,该包装器记录发出的请求
type logWrapper struct {
client.Client
}
func (l *logWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
fmt.Printf("[wrapper] client request to service: %s endpoint: %s\n", req.Service(), req.Endpoint())
return l.Client.Call(ctx, req, rsp)
}
// 实现 client.Wrapper 作为日志包装器 logWrapper
func logWrap(c client.Client) client.Client {
return &logWrapper{c}
}
创建服务时可以初始化
service := micro.NewService(
micro.Name("greeter"),
// wrap the client
micro.WrapClient(logWrap),
)
推荐文章: