Laravel 速率限制器

2024-03-28

我对 Laravel 相当陌生,目前使用的 API 限制为每分钟 25 个请求。 我有一个控制器方法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?
}

我找到了这个类Illuminate\Cache\RateLimiter我认为可能有用,但还不知道如何使用它。谁能直接指出我的正确方向吗?因此基本上,只有在未达到 25 个请求/分钟的限制时,请求才应“等待”并执行。

Thanks!


The Illuminate\Cache\RateLimiter班级有hit and tooManyAttempts你可以这样使用方法:

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';
}

See Illuminate\Cache\RateLimiter https://github.com/laravel/framework/blob/master/src/Illuminate/Cache/RateLimiter.php类以获取更多可用方法。

您还可以检查Illuminate\Foundation\Auth\ThrottlesLogins https://github.com/laravel/ui/blob/master/auth-backend/ThrottlesLogins.php作为示例来了解如何使用Illuminate\Cache\RateLimiter class.

Note: The RateLimiter方法使用秒而不是分钟,因为 Laravel >= 5.8 并得到了重大改进 https://github.com/laravel/framework/pull/32726在 v8.x 上。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Laravel 速率限制器 的相关文章

随机推荐