我想要的:
一个允许每分钟n 个请求的限制器。
我尝试了什么:
(somewhere during init procedure)
limiter = rate.NewLimiter(rate.Every(1*time.Minute/2), 2)
然后在我的 HTTP 服务器的中间件中:
func (self *Router) limiterMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) {
if !limiter.Allow(){
http.Error(responseWriter, "Too many requests", http.StatusTooManyRequests)
return
}
next.ServeHTTP(responseWriter, request)
})
}
据我了解,这应该允许每分钟 2 个请求。然后我尝试发送几个请求,前两个请求之间有 15 秒的暂停,然后大约每秒 1 个请求。
期待:
前两个请求工作
后续请求获得 HTTP429,直到 1 分钟过去,第一个成功的请求被“清除”
另一个请求有效
后续请求获得 HTTP429,直到 15 秒通过,并且初始的第二个请求被“清除”
实际结果:
22/10/31 14:02:31 access: 200 POST /some/path
22/10/31 14:02:46 access: 200 POST /some/path
22/10/31 14:02:47 access: 429 POST /some/path
22/10/31 14:02:48 access: 429 POST /some/path
22/10/31 14:02:49 access: 429 POST /some/path
22/10/31 14:02:50 access: 429 POST /some/path
22/10/31 14:02:51 access: 429 POST /some/path
22/10/31 14:02:52 access: 429 POST /some/path
22/10/31 14:02:53 access: 429 POST /some/path
22/10/31 14:02:54 access: 429 POST /some/path
22/10/31 14:02:55 access: 429 POST /some/path
22/10/31 14:02:56 access: 429 POST /some/path
22/10/31 14:02:57 access: 429 POST /some/path
22/10/31 14:02:58 access: 429 POST /some/path
22/10/31 14:02:59 access: 429 POST /some/path
22/10/31 14:03:00 access: 429 POST /some/path
22/10/31 14:03:01 access: 200 POST /some/path
22/10/31 14:03:02 access: 429 POST /some/path
22/10/31 14:03:03 access: 429 POST /some/path
22/10/31 14:03:04 access: 429 POST /some/path
22/10/31 14:03:05 access: 429 POST /some/path
从日志中可以看到,在最初的2次请求之后,30s后发生了第三次成功的请求。这意味着,在 30s 的正常运行时间内,有 3 个请求成功,而应该只有 2 个。第四个成功的请求在 30s 后再次发生(总共 60s)。
如果我将 bursts 设置为 1,那么最初只有 1 个请求成功,并且每 30 秒就会有一个请求成功。
所以我不确定我应该如何配置限制器来实现我想要的(每分钟普通n 个请求)。
我究竟做错了什么?这甚至可以使用内置限制器来实现,还是我需要一个不同的库来完成这个任务?
慕田峪9158850
相关分类