0

我正在使用一个名为 Artillery 的负载测试工具来模拟我的 Laravel 应用程序上的请求。默认情况下,Laravel 应用程序使用 IP 来检测它是否应该限制速率,因此在生产中不同的 IP 地址不会成为问题,但对于 Artillery,这是一个问题,因为请求返回 429 错误。

我尝试configureRateLimiting在生产中禁用,但仍然出现 429 错误。

Artillery 每秒至少向我的 api 端点发送至少 3 个请求,持续至少 2 分钟,然后在 15 分钟内增加到大约每秒 30 个请求。

在这里禁用速率限制我缺少什么?

<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * The path to the "home" route for your application.
     *
     * This is used by Laravel authentication to redirect users after login.
     *
     * @var string
     */
    public const HOME = '/home';

    /**
     * The controller namespace for the application.
     *
     * When present, controller route declarations will automatically be prefixed with this namespace.
     *
     * @var string|null
     */
    // protected $namespace = 'App\\Http\\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        if (!config('artillery.enabled')) {
            $this->configureRateLimiting();
        }

        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));
        });
    }

    /**
     * Configure the rate limiters for the application.
     *
     * @return void
     */
    protected function configureRateLimiting()
    {
        if (config('artillery.enabled')) {
            return;
        }

        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(300)->by(optional($request->user())->id ?: $request->ip());
        });
    }
}

我的网站通过 Cliudflare,我正在向我的生产端点发送请求,因为这是最现实的测试。

4

1 回答 1

1

app/Http/Kernel.php 中,Laravel 对所有 api 路由都有一个默认的油门限制。

protected $middlewareGroups = [
    ...
    'api' => [
        'throttle:60,1',   //comment means it would be no limit
    ],
];

评论或增加它。

于 2022-01-20T12:36:08.620 回答