使用sleep()来避免命中率限制不起作用

时间:2017-12-28 21:48:28

标签: php api limit endpoint rate

我正在使用我正在使用的API的速率限制而且我很困惑,因为我用来防止这种情况的方法看起来肯定应该可行,但它不能100%的时间工作。我在每个API调用之前都有这行,它应该调用一个函数来检查我是否接近我的极限,如果我是,那么睡眠时间足以重置我的命中数。像这样:

if (isset($http_response_header)) {rateLimit($http_response_header);} 
file_get_contents($endpointURL);

这是功能:

function rateLimit($header)
{
// get hit count from $header

// $count[0] is how many hits per second
// I have a limit of 20 per second

// $count[1] is how many hits per 2 minutes
// I have a limit of 100 per 2 minutes

if ($count[0] == 19) {sleep(1); return;}
if ($count[1] == 99) {sleep(120); return;}
}

如果我每秒拨打最大呼叫数,它应该睡1秒钟,如果我每2分钟拨打一次最大呼叫则睡2分钟。我的代码是否有问题,或者说API错误地限制了我是否有问题?

这是整个rateLimit函数,因为有人想知道我是如何解析它的:

function rateLimit($header)
{
$pos1 = strpos($header[7], ' ') + 1;
$pos2 = strpos($header[7], ':', $pos1);
$count[0] = substr($header[7], $pos1, ($pos2 - $pos1));

$pos1 = strpos($header[7], ',') + 1;
$pos2 = strpos($header[7], ':', $pos1);
$count[1] = substr($header[7], $pos1, ($pos2 - $pos1));

if ($count[0] == 18) {sleep(1); return;}
if ($count[1] == 98) {sleep(120); return;}
}

2 个答案:

答案 0 :(得分:0)

您的$count函数中没有rateLimit定义为数组,因此您可能会收到一个未定义的索引警告,这会破坏您的代码。

所以要么这样做

function rateLimit($header)
{
    $count = [];    

    $pos1 = strpos($header[7], ' ') + 1;
    $pos2 = strpos($header[7], ':', $pos1);
    $count[0] = substr($header[7], $pos1, ($pos2 - $pos1));

    $pos1 = strpos($header[7], ',') + 1;
    $pos2 = strpos($header[7], ':', $pos1);
    $count[1] = substr($header[7], $pos1, ($pos2 - $pos1));

    if ($count[0] == 18) {sleep(1); return;}
    if ($count[1] == 98) {sleep(120); return;}
}

或者

function rateLimit($header)
{
    $pos1 = strpos($header[7], ' ') + 1;
    $pos2 = strpos($header[7], ':', $pos1);

    $pos1 = strpos($header[7], ',') + 1;
    $pos2 = strpos($header[7], ':', $pos1);

    if (substr($header[7], $pos1, ($pos2 - $pos1)) == 18) {sleep(1); return;}
    if (substr($header[7], $pos1, ($pos2 - $pos1)) == 98) {sleep(120); return;}
}

答案 1 :(得分:0)

问题原来是我总是在键7中查找字符串,告诉我我的点击次数,但有时会出现在另一个键中。