拦截器与中间件
拦截器用于在 RPC 调用前后执行自定义逻辑。
一元拦截器
go
func UnaryInterceptor(ctx context.Context, req interface{},
info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
// 前置处理
log.Printf("Request: %s", info.FullMethod)
// 调用处理器
resp, err := handler(ctx, req)
// 后置处理
log.Printf("Response: %v", resp)
return resp, err
}
// 注册拦截器
s := grpc.NewServer(grpc.UnaryInterceptor(UnaryInterceptor))流拦截器
go
func StreamInterceptor(srv interface{}, ss grpc.ServerStream,
info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
log.Printf("Stream Request: %s", info.FullMethod)
return handler(srv, ss)
}客户端拦截器
go
func UnaryClientInterceptor(ctx context.Context, method string,
req, reply interface{}, cc *grpc.ClientConn,
invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
start := time.Now()
err := invoker(ctx, method, req, reply, cc, opts...)
log.Printf("Method: %s, Duration: %v", method, time.Since(start))
return err
}
conn, _ := grpc.Dial("localhost:50051",
grpc.WithUnaryInterceptor(UnaryClientInterceptor))应用场景
- 日志记录
- 认证授权
- 性能监控
- 错误处理