1:composer下载安装think-throttle
composer require topthink/think-throttle
2:组件以中间件的方式进行工作,因此它的开启与其他中间件一样,例如在全局中间件中使用 app/middleware.php
return [
\think\middleware\Throttle::class,
];
3:在 config/throttle.php 配置选项
// 中间件配置
return [
// 缓存键前缀,防止键值与其他应用冲突
'prefix' => 'throttle_',
// 缓存的键,true 表示使用来源ip
'key' => true,
// 要被限制的请求类型, eg: GET POST PUT DELETE HEAD
'visit_method' => ['GET'],
// 设置访问频率,例如 '10/m' 指的是允许每分钟请求10次。值 null 表示不限制, eg: null 10/m 20/h 300/d 200/300
'visit_rate' => '100/m',
// 访问受限时返回的响应
'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);
},
];
4:中间件加入路由后面频繁限制
->middleware(\think\middleware\Throttle::class, [
'visit_rate' => '5/m',
'key' => '__CONTROLLER__/__ACTION__/__IP__',
]);