如何在 Laravel 版本 8 中设置每秒的速率限制器

Mah*_*ish 11 php rate-limiting laravel laravel-8

如何在Laravel 8中设置每秒速率限制器。我需要设置每秒而不是每分钟的速率限制器。

速率限制器 (Laravel 8) - https://laravel.com/docs/8.x/routing#rate-limiting

现在我可以使用 Laravel 的速率限制器几分钟、几小时等。但我正在尝试实现一秒钟的速率限制器。我想限制每秒 25 个请求。(从“Illuminate\Cache\RateLimiting\Limit”导出的 Limit 类)

请检查我使用过的以下代码

RateLimiter::for('api', function (Request $request) {
        return [
            // Rate limiter based on Client IP Address
            Limit::perMinute(env('IP_ADDR_RATE_LIMITER_PER_MINUTE', 60))->by($request->ip())->response(function () {
                ....
            }),
            // Rate limiter based on API key/User
            Limit::perMinute(env('API_KEY_RATE_LIMITER_PER_MINUTE', 60))->by($request->input('key'))->response(function () {
                ...
            })
        ];
    });
Run Code Online (Sandbox Code Playgroud)

有没有办法限制每秒 25 个请求?

注意:还尝试在 Illuminate\Cache\RateLimiting\Limit 中添加/更改函数,其中我尝试更改每分钟函数。提前致谢。

小智 5

在第四个位置通过最大秒数

$executed = RateLimiter::attempt(
    'send-message:'.$user->id,
    $perMinute = 5,
    function() {
        // Send message...
    },  1 // this would be one second
);
Run Code Online (Sandbox Code Playgroud)

这将是每秒 5 次尝试


Liu*_*eña 2

<?php

namespace App\Http\Cache;

class Limit extends \Illuminate\Cache\RateLimiting\Limit
{
    
    /**
     * Create a new limit instance.
     *
     * @param  mixed|string  $key
     * @param  int  $maxAttempts
     * @param  int|float  $decayMinutes
     * @return void
     */
    public function __construct($key = '', int $maxAttempts = 60, $decayMinutes = 1)
    {
        $this->key = $key;
        $this->maxAttempts = $maxAttempts;
        $this->decayMinutes = $decayMinutes;
    }

    /**
     * Create a new rate limit using seconds as decay time.
     *
     * @param  int  $decaySeconds
     * @param  int  $maxAttempts
     * @return static
     */
    public static function perSeconds($decaySeconds, $maxAttempts)
    {
        return new static('', $maxAttempts, $decaySeconds/60.0);
    }
   
}
Run Code Online (Sandbox Code Playgroud)

您可以重新定义 Limit 类

  • 这似乎不起作用,因为从这里返回的内部函数只接受整数类型而不接受浮点类型。我得到了与使用分钟速率限制器相同的结果。 (5认同)