Laravel API 速率限制器的使用

巴啦啦臭魔仙發表於2022-03-25

快取配置

通常情況下,限流器使用你預設的快取驅動,由 cache 配置檔案中的 default 鍵定義。你也可以通過在你的應用程式的 cache 配置檔案中定義一個 limiter 來指定限流器應該使用哪一個快取來驅動:

'default' => 'memcached',
'limiter' => 'redis',

使用

throttle 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)) {
                // 此處為修改後的自定義響應
                return $this->fail(ResponseEnum::HTTP_ACTION_COUNT_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 協議》,轉載必須註明作者和本文連結

相關文章