我想要的:一個允許每分鐘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/path22/10/31 14:02:46 access: 200 POST /some/path22/10/31 14:02:47 access: 429 POST /some/path22/10/31 14:02:48 access: 429 POST /some/path22/10/31 14:02:49 access: 429 POST /some/path22/10/31 14:02:50 access: 429 POST /some/path22/10/31 14:02:51 access: 429 POST /some/path22/10/31 14:02:52 access: 429 POST /some/path22/10/31 14:02:53 access: 429 POST /some/path22/10/31 14:02:54 access: 429 POST /some/path22/10/31 14:02:55 access: 429 POST /some/path22/10/31 14:02:56 access: 429 POST /some/path22/10/31 14:02:57 access: 429 POST /some/path22/10/31 14:02:58 access: 429 POST /some/path22/10/31 14:02:59 access: 429 POST /some/path22/10/31 14:03:00 access: 429 POST /some/path22/10/31 14:03:01 access: 200 POST /some/path22/10/31 14:03:02 access: 429 POST /some/path22/10/31 14:03:03 access: 429 POST /some/path22/10/31 14:03:04 access: 429 POST /some/path22/10/31 14:03:05 access: 429 POST /some/path從日志中可以看到,在最初的2次請求之后,30s后發生了第三次成功的請求。這意味著,在 30s 的正常運行時間內,有 3 個請求成功,而應該只有 2 個。第四個成功的請求在 30s 后再次發生(總共 60s)。如果我將 bursts 設置為 1,那么最初只有 1 個請求成功,并且每 30 秒就會有一個請求成功。所以我不確定我應該如何配置限制器來實現我想要的(每分鐘普通n 個請求)。我究竟做錯了什么?這甚至可以使用內置限制器來實現,還是我需要一個不同的庫來完成這個任務?
1 回答

慕田峪9158850
TA貢獻1794條經驗 獲得超7個贊
Limiter
實現令牌桶算法,該算法實質上按規定的時間間隔提供令牌。
您在評論中提到了滑動窗口:我不相信用于速率限制的滑動窗口的“標準”實現會與您所追求的行為完全匹配。https://konghq.com/blog/how-to-design-a-scalable-rate-limiting-algorithm下描述的方法表明應該使用固定窗口的權重,我已經看到了這種方法的實現。也就是說,這仍然是一個不錯的方法 - 像https://github.com/Narasimha1997/ratelimiter這樣的庫可能會為你處理這個問題。
您所描述的行為似乎更符合鏈接文章中描述為“滑動日志”的行為,盡管考慮到它描述的警告,但您可以尋求實現。
- 1 回答
- 0 關注
- 197 瀏覽
添加回答
舉報
0/150
提交
取消