gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 21:09:38 27 4
gpt4 key购买 nike

我正在寻找一种以高粒度单独限制 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
),
)

关于go - gRPC:基于每个 RPC 限制 API 速率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62925871/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com