30

laravel8更新之速率限制改进

 3 years ago
source link: https://www.wjcms.net/archives/laravel8更新之速率限制改进
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Laravel的请求速率限制器功能已增强,具有更大的灵活性和功能,同时仍保持与先前版本的throttle中间件API的向后兼容性。

J7juYby.jpg!mobile

速率限制器是使用RateLimiter立面的for方法定义的。该for方法接受一个速率限制器名称和一个Closure,该Closure返回应应用于分配了该速率限制器的路由的限制配置:

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;

RateLimiter::for('global', function (Request $request) {
    return Limit::perMinute(1000);
});

由于速率限制器回调接收传入的HTTP请求实例,因此您可以根据传入的请求或经过身份验证的用户动态构建适当的速率限制:

RateLimiter::for('uploads', function (Request $request) {
    return $request->user()->vipCustomer()
                ? Limit::none()
                : Limit::perMinute(100);
});

有时您可能希望将速率限制按任意值进行细分。例如,您可能希望允许用户每个IP地址每分钟100次访问给定路由。为此,您可以by在建立速率限制时使用以下方法:

RateLimiter::for('uploads', function (Request $request) {
    return $request->user()->vipCustomer()
                ? Limit::none()
                : Limit::perMinute(100)->by($request->ip());
});

可以使用throttle 中间件将速率限制器附加到路由或路由组。油门中间件接受您希望分配给路线的速率限制器的名称:

Route::middleware(['throttle:uploads'])->group(function () {
    Route::post('/audio', function () {
        //
    });

    Route::post('/video', function () {
        //
    });
});

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK