Last active
April 7, 2017 10:55
-
-
Save theharveyz/d16b92cd8d20b0fe2047fd30b20c28fd to your computer and use it in GitHub Desktop.
curl_multi 批处理
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function rolling_curl($curl_multi_data = []) | |
{ | |
$queue = curl_multi_init(); | |
$map = array(); | |
foreach ($curl_multi_data as $curl_data) { | |
$ch = curl_init(); | |
$data = $curl_data['data']; | |
if($curl_data['is_post']) | |
{ | |
curl_setopt($ch, CURLOPT_POST, TRUE); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); | |
} | |
curl_setopt($ch, CURLOPT_URL, $curl_data['api']); | |
curl_setopt($ch, CURLOPT_TIMEOUT, 1); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
curl_setopt($ch, CURLOPT_HEADER, 0); | |
curl_setopt($ch, CURLOPT_NOSIGNAL, true); | |
$header = array(); | |
if(@$data['is_ajax']) | |
{ | |
$header[] = 'X-REQUESTED-WITH: XMLHttpRequest'; | |
} | |
curl_setopt($ch, CURLOPT_HTTPHEADER, $header); | |
curl_multi_add_handle($queue, $ch); | |
$map[(string) $ch] = $curl_data['api']; | |
} | |
$responses = array(); | |
do { | |
/** | |
* 对curl队列进行遍历,当请求有完成的请求时,返回的code不为 CURLM_CALL_MULTI_PERFORM (实为 -1) | |
* @var [type] | |
*/ | |
while (($code = curl_multi_exec($queue, $active)) == CURLM_CALL_MULTI_PERFORM) ; | |
/** | |
* 当code为 CURLM_OK 0时,则代表队列完成 | |
*/ | |
if ($code != CURLM_OK) { break; } | |
/** | |
* 当队列完成后,select出 | |
*/ | |
// a request was just completed -- find out which one | |
while ($done = curl_multi_info_read($queue)) { | |
// get the info and content returned on the request | |
$info = curl_getinfo($done['handle']); | |
$error = curl_error($done['handle']); | |
// $results = callback(curl_multi_getcontent($done['handle']), $delay); | |
$responses[$map[(string) $done['handle']]] = compact('info', 'error', 'results'); | |
// remove the curl handle that just completed | |
curl_multi_remove_handle($queue, $done['handle']); | |
curl_close($done['handle']); | |
} | |
// Block for data in / output; error handling is done by curl_multi_exec | |
/** | |
* 当错误发生时,进行阻塞,不再遍历queue,直到批处理文件中有活动链接 | |
*/ | |
if ($active > 0) { | |
curl_multi_select($queue, 0.5); | |
} | |
} while ($active); | |
curl_multi_close($queue); | |
return $responses; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment