From d9d9f8e700db01846b72e6fd81231c7e4d7d63e4 Mon Sep 17 00:00:00 2001 From: royee Date: Thu, 9 Feb 2023 19:52:54 +0800 Subject: [PATCH] rate_limit --- app/Middleware/Kernel.php | 1 + app/Middleware/RateLimitMiddleware.php | 38 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 app/Middleware/RateLimitMiddleware.php diff --git a/app/Middleware/Kernel.php b/app/Middleware/Kernel.php index c38e1f6..47232a9 100644 --- a/app/Middleware/Kernel.php +++ b/app/Middleware/Kernel.php @@ -16,6 +16,7 @@ public static function getMiddlewares(): array return [ TestMiddleware::class => TestMiddleware::class, AuthMiddleware::class => AuthMiddleware::class, + RateLimitMiddleware::class => RateLimitMiddleware::class, ]; } } diff --git a/app/Middleware/RateLimitMiddleware.php b/app/Middleware/RateLimitMiddleware.php new file mode 100644 index 0000000..ec796a3 --- /dev/null +++ b/app/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