【问题标题】:Json API Rate LimitingJson API 速率限制
【发布时间】:2020-11-04 17:08:37
【问题描述】:

example.com/series/title-series-A/ 使用 wordpress 插件缓存 1 天,但是当 缓存过期 并且访问者访问帖子系列

下面的示例访问者同时访问 url

  • example.com/series/title-series-A/
  • example.com/series/title-series-B/
  • example.com/series/title-series-C/

所以所有被访问者访问的系列都会同时请求api,有什么解决方案吗?

(在这所有 posttype 'series' 都有 api php 请求)

function curl_get_contents($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}
$agent  = array('http' => array('user_agent' => 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0'));
        $api = 'https://api.example.com/v3/title-series-here';
        $results = curl_get_contents($api, false, stream_context_create($agent));
    $results = json_decode($results, true);

而且 api.example.com 对每个请求有 4 秒的速率限制,如果超过这个将被阻止

【问题讨论】:

  • 只需添加一个 sleep(5);在每个请求之后。代码将“暂停”5秒
  • 但是所有的post series请求会暂停5秒吗?还是只是 api 请求?因为发布a、b、c同时访问,同时暂停5秒?

标签: php json wordpress api file-get-contents


【解决方案1】:

是的,您需要在 curl_get_content() 函数中添加睡眠:

    function curl_get_contents($url)
    {
        $ch = curl_init();
    
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
    
        $data = curl_exec($ch);
        sleep(5); // here after the request will sleep 5 seconds to permit the rate limit
    
    curl_close($ch);
    
        return $data;
    }
    $agent  = array('http' => array('user_agent' => 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0'));
            $api = 'https://api.example.com/v3/title-series-here';
            $results = curl_get_contents($api, false, stream_context_create($agent));
        $results = json_decode($results, true);

【讨论】:

  • 感谢您的回答,但我认为在 localhost 中测试后是不可能的,如果我使用 sleep() 则页面加载会因为睡眠功能而变长。或者我问错了,如果 3 个页面同时加载 api,我如何允许速率限制?
  • 这很正常,如果您不想影响加载,您必须更改调用 API 以及调用 API 的方式。也许使用 cron 或其他方法。
【解决方案2】:

这是我的解决方案:

  • 检查响应头 api,如果头响应 429 使用 sleep(5);或死();
if(($httpcode == 429)) { sleep(5); }
  • 缓存卷曲结果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    相关资源
    最近更新 更多