Laravel 8 访问限制 throttle 中间件

1,072次阅读
没有评论

throttle 中间件介绍
频率限制经常用在 API 中,用于限制独立请求者对特定 API 的请求频率。每个 API 都会选择一个自己的频率限制时间跨度,GitHub 选择的是 1 小时,Laravel 中间件选择的是 1 分钟。
例如:throttle:60,1,即设置频率限制为每分钟 60 次,如果一个 IP 一分钟内超过这个限制,那么服务器就会返回 429 Too Many Attempts. 响应。

自定义 throttle 中间件
大家可以参看这两篇文章
Laravel 访问限制 throttle 中间件
Laravel API throttle 原理分析
在这两篇文章中,讲了如何自定义一个 throttle 中间件。

在 laravel8 中使用 throttle 中间件
我们通常在这里一般会使用 throttle 中间件来做一个限定条件的速率限定,比如说不在 IP 白名单中的 IP 限制一分钟访问多少次。相对于之前来说,laravel8 中的 throttle 中间件,有了更简单的使用方法。
首先我们可以看到在 Kernel.php 文件中有这样的定义

/**
 * The application's route middleware groups.
 *
 * @var array<string, array<int, class-string|string>>
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array<string, class-string|string>
 */
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];

很明显看到其实 laravel8 中定义的’throttle’ => \Illuminate\Routing\Middleware\ThrottleRequests::class, 是框架已经定义好的,并且在 api 中使用的是 throttle:api。
当然,一般的大家的用法可能就是在这里把 throttle:api 注释掉,新建一个 throttle 中间件或者是在路由中可以直接使用 throttle:60,1 这样的。
那如果是需要做一些复杂的判断,比如说我有很多个 IP 白名单想要排除掉,不做速率限制,或者是有个 VVVIP 用户不限制速率的时候怎么办呢?
这时,我们可以在 laravel8 中找到 App\Providers\RouteServiceProvider.php 文件,在文件最下面我们可以看到这样的写法

/**
 * Configure the rate limiters for the application.
 *
 * @return void
 */
protected function configureRateLimiting()
{
    RateLimiter::for('api', function (Request $request) {
        return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
    });
}

这里定义的 api 就是上面在 Kernel.php 文件中所使用的的 throttle:api。在这里,我们可以设定自定义的速率限制条件,比如说限制用户 IP 白名单之外的 IP 访问限制为每小时 60 次,白名单每次可以访问 1000 次

RateLimiter::for(‘apiHour’, function (Request $request) {
if(!in_array($request->ip(), config(‘ip.whitelist’))){
return Limit::perHour(60)->by($request->ip());
}else{
return Limit::perHour(1000)->by($request->ip());
}
});
当然别忘记在 config 文件夹中新建 ip.php 文件

return [
‘whitelist’ => [
‘192.168.0.1’,
],
];
温馨提示:在使用的时候,用的是 api 接口路由的话,如果想使用自定义的 throttle:apiHour 不要忘记把原来 Kernel.php 中的 throttle:api 注释掉哟!
最后我们就可以在路由中快乐的使用自定义的速率控制中间件了

Route::group([
‘middleware’ => [‘throttle:apiHour’]
], function ($router) {
Route::get(‘user’, function (Request $request) {
return $request->user();
});
});
异常处理
throttle 速率器的异常提示是英文的 Too Many Attemps, 在 laravel8 中,我们可以在 app/Exceptions/Handler.php 文件中重新定义 throttle 速率器的异常提示。

public function register()
{
    ......

    //请求速率问题
    $this->renderable(function (ThrottleRequestsException $e) {
        return response()->json([
            'code' => $e->getCode() ?? 0,
            'message' => "请求过快,请一分钟后再重新尝试!"
        ]);
    });

    //日常错误返回
    ......
}

注意:throttle 速率器的异常返回要放到系统异常返回之前,否则是不会起作用的。

正文完
可以使用微信扫码关注公众号(ID:xzluomor)
post-qrcode
 0
评论(没有评论)

文心AIGC

2023 年 11 月
 12345
6789101112
13141516171819
20212223242526
27282930  
文心AIGC
文心AIGC
人工智能ChatGPT,AIGC指利用人工智能技术来生成内容,其中包括文字、语音、代码、图像、视频、机器人动作等等。被认为是继PGC、UGC之后的新型内容创作方式。AIGC作为元宇宙的新方向,近几年迭代速度呈现指数级爆发,谷歌、Meta、百度等平台型巨头持续布局
文章搜索
热门文章
清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开

清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开

清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开 Jay 2026-01-08 20:18:...
训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享

训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享

训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享 衡宇 2026-01-08 20:...
「北京版幻方」冷不丁开源SOTA代码大模型!一张3090就能跑,40B参数掀翻Opus-4.5和GPT-5.2

「北京版幻方」冷不丁开源SOTA代码大模型!一张3090就能跑,40B参数掀翻Opus-4.5和GPT-5.2

「北京版幻方」冷不丁开源SOTA代码大模型!一张3090就能跑,40B参数掀翻Opus-4.5和GPT-5.2...
开源“裸考”真实世界,国产具身智能基座模型拿下全球第二!

开源“裸考”真实世界,国产具身智能基座模型拿下全球第二!

开源“裸考”真实世界,国产具身智能基座模型拿下全球第二! 西风 2026-01-08 19:02:20 来源:...
最新评论
ufabet ufabet มีเกมให้เลือกเล่นมากมาย: เกมเดิมพันหลากหลาย ครบทุกค่ายดัง
tornado crypto mixer tornado crypto mixer Discover the power of privacy with TornadoCash! Learn how this decentralized mixer ensures your transactions remain confidential.
ดูบอลสด ดูบอลสด Very well presented. Every quote was awesome and thanks for sharing the content. Keep sharing and keep motivating others.
ดูบอลสด ดูบอลสด Pretty! This has been a really wonderful post. Many thanks for providing these details.
ดูบอลสด ดูบอลสด Pretty! This has been a really wonderful post. Many thanks for providing these details.
ดูบอลสด ดูบอลสด Hi there to all, for the reason that I am genuinely keen of reading this website’s post to be updated on a regular basis. It carries pleasant stuff.
Obrazy Sztuka Nowoczesna Obrazy Sztuka Nowoczesna Thank you for this wonderful contribution to the topic. Your ability to explain complex ideas simply is admirable.
ufabet ufabet Hi there to all, for the reason that I am genuinely keen of reading this website’s post to be updated on a regular basis. It carries pleasant stuff.
ufabet ufabet You’re so awesome! I don’t believe I have read a single thing like that before. So great to find someone with some original thoughts on this topic. Really.. thank you for starting this up. This website is something that is needed on the internet, someone with a little originality!
ufabet ufabet Very well presented. Every quote was awesome and thanks for sharing the content. Keep sharing and keep motivating others.
热评文章
OpenAI推理第一人离职,7年打造了o3/o1/GPT-4/Codex

OpenAI推理第一人离职,7年打造了o3/o1/GPT-4/Codex

OpenAI推理第一人离职,7年打造了o3/o1/GPT-4/Codex 衡宇 2026-01-06 13:0...
杜比在CES 2026重塑了观影、娱乐的方式

杜比在CES 2026重塑了观影、娱乐的方式

杜比在CES 2026重塑了观影、娱乐的方式 十三 2026-01-07 12:47:06 来源:量子位 树立...
全自主、更好用!北京人形 “干活机器人” 惊艳亮相 CES2026

全自主、更好用!北京人形 “干活机器人” 惊艳亮相 CES2026

全自主、更好用!北京人形 “干活机器人” 惊艳亮相 CES2026 量子位的朋友们 2026-01-06 16...
港科大教授实测AI眼镜“作弊”:30分钟碾压95%的学生,把传统教学评估体系整破防了

港科大教授实测AI眼镜“作弊”:30分钟碾压95%的学生,把传统教学评估体系整破防了

港科大教授实测AI眼镜“作弊”:30分钟碾压95%的学生,把传统教学评估体系整破防了 梦瑶 2026-01-0...