使用 golang 服务器的第三方 API 的速率限制

您好,我有一个使用第三方 API 的带有 gorilla-mux 的 Go 后端。我有一些向此 API 发出请求的处理程序。我的限制是每秒 5 个请求。

我如何实现某种整体速率限制系统,其中请求排队并仅在容量可用时发送(或五个插槽中的一个是空闲的)?谢谢。


慕雪6442864
浏览 208回答 3
3回答

狐的传说

对于对 3rd 方 API 的速率限制请求,您可以使用 Golang library golang.org/x/time/rate。示例用法package mainimport (&nbsp; &nbsp; "context"&nbsp; &nbsp; "log"&nbsp; &nbsp; "net/http"&nbsp; &nbsp; "time"&nbsp; &nbsp; "golang.org/x/time/rate")func main() {&nbsp; &nbsp; rl := rate.NewLimiter(rate.Every(10*time.Second), 50)&nbsp; &nbsp; reqURL := "https://www.google.com"&nbsp; &nbsp; c := http.Client{}&nbsp; &nbsp; req, err := http.NewRequest("GET", reqURL, nil)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal("failed to create request: %v", err)&nbsp; &nbsp; }&nbsp; &nbsp; for i := 0; i < 300; i++ {&nbsp; &nbsp; &nbsp; &nbsp; // Waiting for rate limiter&nbsp; &nbsp; &nbsp; &nbsp; err = rl.Wait(context.Background())&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Println("failed to wait: %v", err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // and doing the requests if the rate is not exceeded&nbsp; &nbsp; &nbsp; &nbsp; _, err := c.Do(req)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Println("failed to wait: %v", err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}重要的!!! 这不是多个实例使用的解决方案!如果您正在生成多个服务器,您应该考虑使用 Redis 来同步限制器 ( https://github.com/go-redis/redis_rate )。

慕后森

也许你可以试试这个:https&nbsp;://github.com/dypflying/leakybucket ,假设漏桶算法速率限制器可能适合你的场景。

红颜莎娜

如果我理解得很好,你有一个应该连接到 API Y 的应用程序 X,并且 X 每秒不能向 Y 发送超过 5 个请求。这是一个复杂且不完整的场景。让我问几个问题X 上的预期负载是多少?如果它低于每秒 5 个请求……没关系X 上的超时时间是多少?想象一下,你每秒收到 50 个请求……在这种情况下,你可能需要 10 秒来回答一些请求,可以吗?在 X 超时的情况下,客户端会重试吗?如果你每秒调用 Y 超过 5 个请求会发生什么?来自 Y 的响应是否可缓存?你有多个服务器/自动缩放吗?一种可能性是在应用程序上设置速率限制器以匹配 API 上的限制。另一个是尽可能多地调用 API。如果由于请求过多而失败,您可以实施重试逻辑或放弃。如果出于某种原因需要非常小心地使用此 API,并且不需要运行多个实例/自动缩放,则解决方案是在应用程序上使用速率限制器。如果你需要运行多个实例,你需要一些东西来集中访问这个 API,这是一件非常微妙的事情……它是一个单点故障。您可以实现一个每秒仅传送 5 个令牌的令牌系统。获得令牌后,您就可以访问 API。这是一种可能性。天下没有免费的午餐。每种解决方案都有利有弊。但是如果你可以避免执行对 API 的请求(比如缓存结果)或者如果你只需要存储数据(并运行异步程序)就将消息添加到队列中……也许会更容易讨论更好的解决方案
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go