登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-23 16:48:33 223浏览 收藏

大家好,我们又见面了啊~本文《gRPC:基于每个 RPC 限制 API 速率》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

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

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


解决方案


我想我可以使用 go-grpc-middleware withunaryserverchain 和一元拦截器发布一个片段以供参考,以了解实际情况。

这个想法是将 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
        ),
    )

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>