From 46b6392f4f380835a9301ed11ed17ff6dc19aa43 Mon Sep 17 00:00:00 2001 From: royee Date: Thu, 9 Feb 2023 19:51:25 +0800 Subject: [PATCH] rate_limit --- .../Middleware/RateLimitMiddleware.php | 38 +++++++++++++++++++ dcr/RateLimit/RateLimitHandler.php | 1 + 2 files changed, 39 insertions(+) create mode 100644 dcr/RateLimit/Middleware/RateLimitMiddleware.php diff --git a/dcr/RateLimit/Middleware/RateLimitMiddleware.php b/dcr/RateLimit/Middleware/RateLimitMiddleware.php new file mode 100644 index 0000000..1a2a70f --- /dev/null +++ b/dcr/RateLimit/Middleware/RateLimitMiddleware.php @@ -0,0 +1,38 @@ +get(RateLimitHandler::class); + // “桶”可以容纳的请求数 + $capacity = 60; + // “桶”完全重新装满所需的时间 + $seconds = 60; + // “桶”此操作使用的令牌数 + $cost = 1; + + if ($throttler->handle($request->getRemoteIp(), $capacity, $seconds, $cost) === false) { + throw new RuntimeException('请求次数太频繁'); + } + + return $next->handle($request); + }; + + } +} \ No newline at end of file diff --git a/dcr/RateLimit/RateLimitHandler.php b/dcr/RateLimit/RateLimitHandler.php index 5cdc58e..48d1fa3 100644 --- a/dcr/RateLimit/RateLimitHandler.php +++ b/dcr/RateLimit/RateLimitHandler.php @@ -74,6 +74,7 @@ private function time(): int /** * Used during testing to set the current timestamp to use. * + * @param int $time * @return $this */ public function setTestTime(int $time): self