Golang throttled是一个基于GCRA的速率限制库
Throttled包实现了对HTTP端点等资源的速率限制访问。它使用通用信元速率算法(GCRA)来限制对资源(如HTTP端点)的访问,从而实现速率限制。2.0.0版本对节流API进行了一些重大更改。如果此更改破坏了您的代码,或者您希望保留旧API的功能,请打开一个问题。我们不保证会有任何特定的更改,但希望了解更多关于用户需求的信息。
Github地址:https://github.com/throttled/throttled
安装
import (
“github.com/throttled/sthrottled/v2”
)
然后,任何标准的Go工具,如构建、测试,都会自动找到包。您也可以使用go-get将其拉入您的项目中:
go get -u github.com/throttled/throttled/v2
如果你以前使用了throttled,现在推荐你升级到最新版本,并升级到含有context的新函数接口。下面的函数可进行替换:请注意,并非所有store都使用了context.Context。memstore.New => memstore.NewCtx
goredisstore.New => goredisstore.NewCtx
redigostore.New => redigostore.NewCtx
throttled.NewGCRARateLimiter => throttled.NewGCRARateLimiterCtx
throttled.HTTPRateLimiter => throttled.HTTPRateLimiterCtx
此示例演示了HTTPLimiter用于对http进行速率限制访问的用法。每分钟每条路径最多可处理20个请求,最多可处理5个附加请求:
package main
import (
"fmt"
"log"
"net/http"
"github.com/throttled/throttled/v2"
"github.com/throttled/throttled/v2/store/memstore"
)
func myHandlerFunc(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, world")
}
func main() {
store, err := memstore.NewCtx(65536)
if err != nil {
log.Fatal(err)
}
quota := throttled.RateQuota{
MaxRate: throttled.PerMin(20),
MaxBurst: 5,
}
rateLimiter, err := throttled.NewGCRARateLimiterCtx(store, quota)
if err != nil {
log.Fatal(err)
}
httpRateLimiter := throttled.HTTPRateLimiterCtx{
RateLimiter: rateLimiter,
VaryBy: &throttled.VaryBy{Path: true},
}
handler := http.HandlerFunc(myHandlerFunc)
http.ListenAndServe(":8080", httpRateLimiter.RateLimit(handler))
}
我们经常在使用第三方API时,会看到这样的提示,该接口频率限制限额,请合理安排业务调用,特别是token的请求,经常会要求你缓存到本地,如果我们的项目供他人使用,也有速率限制时,可以集成这个库方便的完成需求。
Github地址:https://github.com/throttled/throttled
Golang · 目录
上一篇Golang 一个3D游戏引擎g3n下一篇EasyDarwin又一款高效的流媒体服务器
技术源泉