Laravel 速率限制器

Jen*_*nny 5 race-condition ratelimit laravel

我对 Laravel 还很陌生,目前正在使用每分钟限制为 25 个请求的 API。我有一个控制器方法sendRequest(),所有方法都使用它来向 API 发送请求,所以我认为这是放置速率限制器的地方,如果尚未达到限制,它会检查当前请求是否可以添加到队列中。

我在想这样的事情:

protected function sendRequest(){
    if ($this->allowRequest()) {
        //proceed to api call
    }
}

protected function allowRequest() {
    $allow = false;
    //probably a do-while loop to check if the limit has been reached within the timeframe?
}
Run Code Online (Sandbox Code Playgroud)

我发现这个类Illuminate\Cache\RateLimiter我认为可能很有用,但还不知道如何使用它。任何人都可以直接指出我正确的方向吗?所以基本上请求应该“等待”并只有在没有达到 25 个请求/分钟限制时才执行。

谢谢!

Haf*_*ari 7

Illuminate\Cache\RateLimiter类有hittooManyAttempts方法,你可以使用这样的:

use Illuminate\Cache\RateLimiter;
use Illuminate\Http\Request;

protected function sendRequest()
{
    if ($this->hasTooManyRequests()) {
        // wait
        sleep(
            $this->limiter()
                ->availableIn($this->throttleKey()) + 1 // <= optional plus 1 sec to be on safe side
        );

        // Call this function again.
        return $this->sendRequest();
    }
    
    //proceed to api call
    $response = apiCall();

    // Increment the attempts
    $this->limiter()->hit(
        $this->throttleKey(), 60 // <= 60 seconds
    );

    return $response;
}

/**
 * Determine if we made too many requests.
 *
 * @return bool
 */
protected function hasTooManyRequests()
{
    return $this->limiter()->tooManyAttempts(
        $this->throttleKey(), 25 // <= max attempts per minute
    );
}

/**
 * Get the rate limiter instance.
 *
 * @return \Illuminate\Cache\RateLimiter
 */
protected function limiter()
{
    return app(RateLimiter::class);
}

/**
 * Get the throttle key for the given request.
 *
 * @return string
 */
protected function throttleKey()
{
    return 'custom_api_request';
}
Run Code Online (Sandbox Code Playgroud)

有关Illuminate\Cache\RateLimiter更多可用方法,请参阅类。

您还可以查看Illuminate\Foundation\Auth\ThrottlesLogins示例以了解如何使用Illuminate\Cache\RateLimiter类。

注意:这些RateLimiter方法使用秒而不是分钟,因为 Laravel >= 5.8 并且在 v8.x 上有了重大改进

  • 这不是“ThrottlesLogins”,我说你可以检查它以了解如何使用“RateLimitter”。 (2认同)