【问题标题】:gRPC: Rate limiting an API on a per-RPC basisgRPC:基于每个 RPC 对 API 进行速率限制
【发布时间】:2020-07-16 00:59:33
【问题描述】:

我正在寻找一种以高粒度分别对 RPC 进行速率限制的方法,但令我沮丧的是,对于这个问题没有太多可用的选项。我正在尝试用 gRPC 替换 REST API,对我来说最重要的功能之一是能够为每个路由添加中间件。不幸的是,go-grpc-middleware 仅将中间件应用于整个服务器。

在我的想象中,一个理想的 gRPC 限速中间件会使用与 go-proto-validators 类似的技巧,其中 proto 文件将包含限速本身的配置。

【问题讨论】:

  • 您是否考虑过实现自己的server interceptorgo-grpc-middleware 建立在拦截器之上。实现您自己的可以让您根据请求信息指定速率限制。
  • 有趣的想法,但是我不确定是否有办法区分通过拦截器调用哪个 RPC。不过看起来很有希望。
  • 想出了一些应该使速率限制成为可能的东西,UnaryServerInfo.FullMethod 似乎为 RPC 显示了一个非常独特的标识符
  • 如果需要,您还应该能够检查 req 参数以找出更具体的信息。

标签: go grpc


【解决方案1】:

我想我可以使用go-grpc-middleware WithUnaryServerChain 和一元拦截器发布一个 sn-p 以供参考。

这个想法是向服务器添加一个grpc.UnaryInterceptor,它将使用*grpc.UnaryServerInfo 的实例来调用。此对象导出字段 FullMethod,其中包含被调用的 RPC 方法的限定名称。

在拦截器中,您可以在实际调用 RPC 处理程序之前执行任意代码,包括特定于 RPC 的速率限制逻辑。

// import grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
// import "google.golang.org/grpc"

    grpcServer := grpc.NewServer(
        // WithUnaryServerChain is a grpc.Server config option that accepts multiple unary interceptors.
        grpc_middleware.WithUnaryServerChain(
            // UnaryServerInterceptor provides a hook to intercept the execution of a unary RPC on the server. info
            // contains all the information of this RPC the interceptor can operate on. And handler is the wrapper
            // of the service method implementation. It is the responsibility of the interceptor to invoke handler
            // to complete the RPC.
            grpc.UnaryInterceptor(func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
                // FullMethod is the full RPC method string, i.e., /package.service/method.
                switch info.FullMethod {
                case "/mypackage.someservice/DoThings":
                    // ... rate limiting code
                    // if all is good, then call the handler
                    return handler(ctx, req)
                }
            }),
            // other `grpc.ServerOption` opts
        ),
    )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多