本文我来介绍 gRPC 中的中间件相关知识。

介绍

gRPC 中间件基于前面讲解的拦截器相关概念,它是一组拦截器、辅助、工具的集合,在我们使用 gRPC 开发应用时,往往会使用到各种中间件。它允许在服务端或客户端以拦截器链条形式应用多个中间件。 因为拦截器经常用来实现一些通用的功能 ,如鉴权认证、日志、监控等,所以使用 gRPC 中间件来实现这些可重用功能是十分合适的。下面的代码就分别暂时服务端和客户端使用中间件的例子:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import "github.com/grpc-ecosystem/go-grpc-middleware"

myServer := grpc.NewServer(
    grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(
        grpc_ctxtags.StreamServerInterceptor(),
        grpc_opentracing.StreamServerInterceptor(),
        grpc_prometheus.StreamServerInterceptor,
        grpc_zap.StreamServerInterceptor(zapLogger),
        grpc_auth.StreamServerInterceptor(myAuthFunction),
        grpc_recovery.StreamServerInterceptor(),
    )),
    grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
        grpc_ctxtags.UnaryServerInterceptor(),
        grpc_opentracing.UnaryServerInterceptor(),
        grpc_prometheus.UnaryServerInterceptor,
        grpc_zap.UnaryServerInterceptor(zapLogger),
        grpc_auth.UnaryServerInterceptor(myAuthFunction),
        grpc_recovery.UnaryServerInterceptor(),
    )),
)
1
2
3
4
5
6
7
import "github.com/grpc-ecosystem/go-grpc-middleware"

clientConn, err = grpc.Dial(
    address,
    grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(monitoringClientUnary, retryUnary)),
    grpc.WithStreamInterceptor(grpc_middleware.ChainStreamClient(monitoringClientStream, retryStream)),
)

常用的中间件

go-grpc-middleware 项目提供了一些常用的中间件:

认证

  • grpc_auth - 一个可定制的(通过AuthFunc)身份验证中间件

日志记录

  • grpc_ctxtags - 将Tag地图添加到上下文的库,数据从请求正文填充
  • grpc_zap - 将zap日志库集成到 gRPC 处理程序中。
  • grpc_logrus - 将logrus日志库集成到 gRPC 处理程序中。
  • grpc_kit - 将go-kit/log日志库集成到 gRPC 处理程序中。
  • grpc_grpc_logsettablegrpclog.LoggerV2 - 一个允许在运行时替换记录器的包装器(线程安全)。

监控

  • grpc_prometheus - Prometheus 客户端和服务器端监控中间件
  • otgrpc - OpenTracing客户端和服务器端拦截器
  • grpc_opentracing - OpenTracing客户端和服务器端拦截器,支持流式处理和处理程序返回的标签
  • otelgrpc - OpenTelemetry客户端和服务器端拦截器

客户端中间件

grpc_retry - 一个通用的 gRPC 响应代码重试机制,客户端中间件

服务端中间件

grpc_validator - 来自.proto选项的代码生成入站消息验证 grpc_recovery - 将恐慌转化为 gRPC 错误 ratelimit - 限流

编写自己的中间件

如果上面提供的中间件不满足你的需求,该如何定制中间件呢,就是使用前面讲解的拦截器来实现。

小结