Laravel API 速率限制器的使用

Laravel框架
431
0
0
2022-09-18
标签   Laravel API
middleware 速率限制器附加到路由或路由组即可throttle 中间件第一个参数是频率(次),第二个参数是时间(分钟)。下面代码块表示 1 分钟最多请求 10 次
Route::get('info', [UserController::class, 'info'])->middleware(['throttle:10,1']);

如果我们在设定的分钟数内请求次数超过了我们设定的频率次数,则会返回如下:

Laravel API 速率限制器的使用

改造

如果我们想要得到 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
}