From 06868e3a1ef235842e7449e204e59c81f968b9d2 Mon Sep 17 00:00:00 2001 From: jsasg <735273025@qq.com> Date: Thu, 2 Jan 2025 16:41:30 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E9=AA=8C=E8=AF=81=E7=A0=81=E5=8A=A0?= =?UTF-8?q?=E9=99=90=E6=B5=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/admin/route/v1.php | 7 ++++++- composer.json | 2 +- config/throttle.php | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 config/throttle.php diff --git a/app/admin/route/v1.php b/app/admin/route/v1.php index 8c3217d1..4a6a94d6 100644 --- a/app/admin/route/v1.php +++ b/app/admin/route/v1.php @@ -15,7 +15,12 @@ Route::group('v1', function () { // 用户模块 Route::group('user', function () { // 获取验证码 - Route::get('captcha', 'Captcha/index'); + Route::get('captcha', 'Captcha/index')->middleware(\think\middleware\Throttle::class, [ + 'visit_rate' => '5/m', + 'visit_fail_response' => function (\think\middleware\Throttle $throttle, \think\Request $request, int $wait_seconds) { + return \think\Response::create('您的操作过于频繁, 请在 ' . $wait_seconds . ' 秒后再试。')->code(429); + }, + ]); // 登录接口 Route::post('login', 'Login/index'); diff --git a/composer.json b/composer.json index 1ef17911..37837433 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,7 @@ "topthink/think-view": "^2.0", "topthink/think-captcha": "^3.0", "thans/tp-jwt-auth": "^2.2", - "topthink/think-throttle": "*" + "topthink/think-throttle": "^2.0" }, "require-dev": { "symfony/var-dumper": ">=4.2", diff --git a/config/throttle.php b/config/throttle.php new file mode 100644 index 00000000..575662e8 --- /dev/null +++ b/config/throttle.php @@ -0,0 +1,33 @@ + 'throttle_', + // 缓存的键,true 表示使用来源ip + 'key' => true, + // 要被限制的请求类型, eg: GET POST PUT DELETE HEAD 等 + 'visit_method' => ['GET', 'HEAD'], + // 设置访问频率,例如 '10/m' 指的是允许每分钟请求10次;'10/60'指允许每60秒请求10次。值 null 表示不限制, eg: null 10/m 20/h 300/d 200/300 + 'visit_rate' => '100/m', + /* + * 设置节流算法,组件提供了四种算法: + * - CounterFixed :计数固定窗口 + * - CounterSlider: 滑动窗口 + * - TokenBucket : 令牌桶算法 + * - LeakyBucket : 漏桶限流算法 + */ + 'driver_name' => CounterFixed::class, + // 响应体中设置速率限制的头部信息 + 'visit_enable_show_rate_limit' => true, + // 访问受限时返回的响应 + 'visit_fail_response' => function (Throttle $throttle, Request $request, int $wait_seconds) { + return Response::create('Too many requests, try again after ' . $wait_seconds . ' seconds.')->code(429); + }, +];