我正在开发一个系统,我需要使用多个GET请求来获取5000多个用户位置。不幸的是,API端点不支持多个客户端ID。即。我必须制作5000多个唯一的get请求来获取它们的位置并使用(累积响应)来进行另一个API调用。
我正在使用CURL发出请求。我使用以下代码段[1]发出请求。
<?php
function multiRequest($data, $options = array()) {
// array of curl handles
$curly = array();
// data to be returned
$result = array();
// multi handle
$mh = curl_multi_init();
// loop through $data and create curl handles
// then add them to the multi-handle
foreach ($data as $id => $d) {
$curly[$id] = curl_init();
$url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d;
curl_setopt($curly[$id], CURLOPT_URL, $url);
curl_setopt($curly[$id], CURLOPT_HEADER, 0);
curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1);
// post?
if (is_array($d)) {
if (!empty($d['post'])) {
curl_setopt($curly[$id], CURLOPT_POST, 1);
curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']);
}
}
// extra options?
if (!empty($options)) {
curl_setopt_array($curly[$id], $options);
}
curl_multi_add_handle($mh, $curly[$id]);
}
// execute the handles
$running = null;
do {
curl_multi_exec($mh, $running);
} while($running > 0);
// get content and remove handles
foreach($curly as $id => $c) {
$result[$id] = curl_multi_getcontent($c);
curl_multi_remove_handle($mh, $c);
}
// all done
curl_multi_close($mh);
return $result;
}
?>
它适用于少量请求,但当我尝试达到1000+时,它会超时。
$data = [];
for ($i = 0; $i < 1000; $i++) {
$data[] = 'https://foo.bar/api/loc/v/queries/location?address=XXXXXXXXX';
}
$token = $this->refresh();
$r = $this->multiRequest($data, $token);
解决此问题的最佳方法是什么?
答案 0 :(得分:0)
有没有办法修改端点API以允许处理多个ID?如果是,那是首选,因为如果您同时运行数千个请求,实际上就会发生类似DDoS攻击的事情。
但是,您可能需要检查PHP的curl_multi_ *函数(http://us3.php.net/manual/en/function.curl-multi-exec.php)。
另一个有用的链接:http://www.onlineaspect.com/2009/01/26/how-to-use-curl_multi-without-blocking/