如何观察PHP中的速率限制?

时间:2016-01-03 18:10:57

标签: php limit rate

所以,我正在从API请求数据。 到目前为止,我的API密钥仅限于:

每10秒发出10次请求 每10分钟发出500次请求

基本上,我想要从用户玩过的每个游戏中请求特定值。 例如,大约有300场比赛。

所以我必须使用PHP发出300个请求。如何减慢速度以观察速率限制? (这可能需要时间,网站不一定要快)

我试过sleep(),这导致我的脚本崩溃..还有其他方法吗?

3 个答案:

答案 0 :(得分:0)

我建议设置一个每分钟执行一次的cron作业,甚至更好地使用Laravel调度,而不是使用sleep或usleep来模仿cron。

以下是两者的一些信息:

https://laravel.com/docs/5.1/scheduling

http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/

答案 1 :(得分:0)

这听起来像是set_time_limit() function的完美用法。此功能允许您指定脚本执行的时间(以秒为单位)。例如,如果您在脚本开头说set_time_limit(45);,则脚本将运行总共45秒。此功能的一个重要功能是,您可以通过说:set_time_limit(0);来允许您的脚本无限期地执行(没有时间限制)。

您可能希望使用以下常规结构编写脚本:

<?php
// Ignore user aborts and allow the script
// to run forever
ignore_user_abort(true);
set_time_limit(0);

// Define constant for how much time must pass between batches of connections:
define('TIME_LIMIT', 10); // Seconds between batches of API requests

$tLast = 0;
while( /* Some condition to check if there are still API connections that need to be made */ ){

    if( timestamp() <= ($tLast + TIME_LIMIT) ){ // Check if TIME_LIMIT seconds have passed since the last connection batch
        // TIME_LIMIT seconds have passed since the last batch of connections
        /* Use cURL multi to make 10 asynchronous connections to the API */

        // Once all of those connections are made and processed, save the current time:
        $tLast = timestamp();
    }else{
        // TIME_LIMIT seconds have not yet passed
        // Calculate the total number of seconds remaining until TIME_LIMIT seconds have passed:
        $timeDifference = $tLast + TIME_LIMIT - timestamp();
        sleep( $timeDifference ); // Sleep for the calculated number of seconds
    }

} // END WHILE-LOOP

/* Do any additional processing, computing, and output */
?>

注意:在此代码段中,我还使用了ignore_user_abort() function。正如代码注释中所述,此函数只允许脚本忽略用户中止,因此如果用户在脚本仍在执行时关闭浏览器(或连接),脚本将继续检索和处理来自API无论如何。您可能希望在实施中禁用它,但我会将其留给您。

显然这段代码非常不完整,但是它应该让你对如何为这个问题实现解决方案有一个很好的理解。

答案 2 :(得分:-1)

不要减慢个别请求的速度。

相反,您通常会使用类似Redis的内容来跟踪每个IP或每个用户的请求。一旦达到限制一段时间,拒绝(可能使用HTTP 429状态代码),直到计数重置。

http://redis.io/commands/INCR加上http://redis.io/commands/expire很容易就可以了。

相关问题