gRPC:基于每个 RPC 限制 API 速率

Blu*_*ipt 2 go grpc

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

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

bla*_*een 6

我想我可以发布一个片段以供参考,使用go-grpc-middleware WithUnaryServerChain和一元拦截器在实践中是什么样子。

这个想法是将 a 添加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
        ),
    )
Run Code Online (Sandbox Code Playgroud)