我有一个网站,从API获取价格。问题是,如果你在短时间内向这个API发送超过10个请求,你的ip会被临时阻塞(我不确定这是本地主机上的问题,还是来自Web服务器的问题,我认为是后者)。
对API的请求返回一个JSON对象,然后我解析该对象并将其某些部分存储到数据库中。数据库中大约有300个条目,所以我需要向这个API发出大约300个请求。
我最终会有一个cron工作,每x小时,所有价格都会从API更新。该作业调用一个php脚本,该脚本完成所有请求和数据库处理。
有没有一种方法可以让脚本在更长的时间内而不是立即发送请求?我遇到的问题是,在大约20个请求之后,ip会被阻止,之后的50个请求不会返回任何数据。
我研究了sleep(),但发现它只会将结果存储在缓冲区中并等待,而不是在每次请求后等待。
以下是cron作业将调用的脚本:
define('HTTP_NOT_FOUND', false);
define('HTTP_TIMEOUT', null);
function http_query($url, $timeout=5000) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT_MS, $timeout);
$text = curl_exec($curl);
if($text) {
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
switch($code){
case 200:
return $text;
case 404:
return -1;
default:
return -1;
}
}
return HTTP_TIMEOUT;
}
function getPrices($ID) {
$t = time();
$url = url_to_API;
$result = http_query($url, 5000);
if ($result == -1) { return -1; }
else {
return json_decode($result)->price;
}
}
connectToDB();
$result = mysql_query("SELECT * FROM prices") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$updatedPrice = getItemPrices($id);
.
.
echo $updatedPrice;
. // here I am just trying to make sure I can get all ~300 prices without getting any php errors or the request failing (since the ip might be blocked)
.
}
sleep()不应影响/缓冲对数据库的查询。如果需要立即打印内容,可以使用ob_flush()。还要确保使用set_time_limit()设置最长执行时间,这样脚本就不会超时。
set_time_limit(600);
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$updatedPrice = getItemPrices($id);
.
.
echo $updatedPrice;
//Sleep 1 seconds, use ob_flush if necessary
sleep(1);
//You can also use usleep(..) to delay the script in milliseconds
}