go - 如何动态增加速率限制器限制?

标签 go

我正在使用 golang.org/x/time/rate用于限制 api 请求的速率。

lim := rate.NewLimiter(rateLimit, burstLimit)

for range time.NewTicker(time.Second).C {
    fmt.Println(time.Now(), "tick")
    go func() {
        res := lim.Reserve()
        if res.OK() && res.Delay() == 0 {
            fmt.Println(time.Now(), "done")
        } else {
            fmt.Println(time.Now(), "dropped")
            res.Cancel()
        }
    }()
}
对于可以立即执行的允许请求,有时可能需要重试请求。那些重试的请求不应计入速率限制。使用 res.Cancel()在这种情况下,由于 https://cs.opensource.google/go/x/time/+/1f47c861:rate/rate.go;l=161,不会将保留的 token 返回到池中.
保留 token 如何取消保留或限制器状态调整?

最佳答案

您要rate.Reservation.Cancel() - 尽最大努力“撤消”保留 - 考虑到速率限制器的并发使用。
从文档:

Cancel is shorthand for CancelAt(time.Now()).

CancelAt indicates that the reservation holder will not perform the reserved action and reverses the effects of this Reservation on the rate limit as much as possible, considering that other reservations may have already been made.

关于go - 如何动态增加速率限制器限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69257714/

相关文章:

list - 为什么 golang list/ring 的 Element 和 Ring 结构?

Golang 导入的字段与标准字段声明的行为不同

mysql - 已建立连接时插入数据库的问题

mongodb - chrome 和 safari 不会在设置了 Content-Length 的 go 服务器提供的 html 模板中呈现图像

http - 如何在 go-chi 中启用 gzip 压缩中间件

go - 二进制补码和 fmt.Printf

json - 在 Golang 中 Umarshalling 这个 JSON

go - 接口(interface)作为结构中的字段,接口(interface)调用将输入作为相同结构的方法

go - Go 中的常量在初始化期间建立

go - 我可以创建一个只能与 defer 一起使用的函数吗?