Laravel API 速率限制器的使用
缓存配置
通常情况下,限流器使用你默认的缓存驱动,由 cache 配置文件中的 default 键定义。你也可以通过在你的应用程序的 cache 配置文件中定义一个 limiter 来指定限流器应该使用哪一个缓存来驱动:
'default' => 'memcached',
'limiter' => 'redis',
使用
将 throttle
middleware 速率限制器附加到路由或路由组即可
throttle 中间件第一个参数是频率(次),第二个参数是时间(分钟)。下面代码块表示 1 分钟最多请求 10 次
Route::get('info', [UserController::class, 'info'])->middleware(['throttle:10,1']);
如果我们在设定的分钟数内请求次数超过了我们设定的频率次数,则会返回如下:
改造
如果我们想要得到 JSON 响应而不是得到一个 HTML,我们可以这样进行操作:
1、在 App\Http\Middleware
目录下创建新的中间件 ThrottleRequests
php artisan make:middleware ThrottleRequests
2、将 \Illuminate\Routing\Middleware\ThrottleRequests
内容复制到 \App\Http\Middleware\ThrottleRequests
内,并修改:
use App\Helpers\ResponseEnum;
use ApiResponse;
protected function handleRequest($request, Closure $next, array $limits)
{
foreach ($limits as $limit) {
if ($this->limiter->tooManyAttempts($limit->key, $limit->maxAttempts)) {
// 此处为修改后的自定义响应
$this->throwBusinessException(ResponseEnum::HTTP_ERROR, '操作频繁');
// throw $this->buildException($request, $limit->key, $limit->maxAttempts, $limit->responseCallback);
}
$this->limiter->hit($limit->key, $limit->decayMinutes * 60);
}
$response = $next($request);
foreach ($limits as $limit) {
$response = $this->addHeaders(
$response,
$limit->maxAttempts,
$this->calculateRemainingAttempts($limit->key, $limit->maxAttempts)
);
}
return $response;
}
3、修改 App\Http
路由中间件 $routeMiddleware
中的 throttle
'throttle' => \App\Http\Middleware\ThrottleRequests::class,
4、测试一下,当我们访问频率大于设定的次数时会返回:
{
"status": "fail",
"code": 200302,
"message": "操作频繁",
"data": null,
"error": null
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
挺详细的,不错 :kissing_heart:
博主为什么要限流呢,普通的场景应该用不到吧,
这个速率限制,有一个 header ,会提示节流的数据,和恢复重置的时间等数据。 经过你的api响应接口后,这个数据就丢了。另外默认的 429 状态码也变成了200 。看要怎么修改调整一下。
用这玩意儿要注意清理缓存 她不会自动清理过期的数据 我服务器index node 就被耗光了
也不知道是什么原因
问一下这个限流中间件是以什么维度计算次数的?比如是不区分用户,不区分ip,只要请求这个接口次数就加1,还是说不同ip进来或者不同用户进来会分别计数?