我正在使用 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/