我对curl_multi()的使用仍然是串行的吗?如果是这样,我该如何并行?
今天有人暗示我的 curl_multi()
代码实际上是串行工作的,而我的希望是并行化 cURL 请求。
我的代码仍然是串行的吗?如果是,我如何并行化?
这是相关代码:
/**
* Returns the cURL responses given multiple target URLs
* @param array $targetUrls Array of target URLs for cURL
*
* @return array cURL Responses
*/
private function getCurlMultiResponses($targetUrls)
{
// Cache the count
$count = count($targetUrls);
// Create the multiple cURL handles
for($i = 0; $i < $count; $i++) {
$ch[$i] = curl_init($targetUrls[$i]);
curl_setopt($ch[$i], CURLOPT_POST, FALSE);
curl_setopt($ch[$i], CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, TRUE);
}
// Initialize the multiple cURL handle
$mh = curl_multi_init();
// Add the handles to the curl_multi handle
for($i = 0; $i < $count; $i++) {
curl_multi_add_handle($mh, $ch[$i]);
}
$running = null;
// Execute the handles
do {
curl_multi_exec($mh, $running);
} while ($running > 0);
$responses = array();
// Remove the handles and return the response
for($i = 0; $i < $count; $i++) {
curl_multi_remove_handle($mh, $ch[$i]);
$responses[$i] = curl_multi_getcontent($ch[$i]);
}
// Close the multiple cURL handle
curl_multi_close($mh);
return $responses;
}
I got a hint from someone today that my curl_multi()
code is actually working in serial, when my hope was to parallelize the cURL requests.
Is my code still serial? If so, how I can parallelize?
Here's the relevant code:
/**
* Returns the cURL responses given multiple target URLs
* @param array $targetUrls Array of target URLs for cURL
*
* @return array cURL Responses
*/
private function getCurlMultiResponses($targetUrls)
{
// Cache the count
$count = count($targetUrls);
// Create the multiple cURL handles
for($i = 0; $i < $count; $i++) {
$ch[$i] = curl_init($targetUrls[$i]);
curl_setopt($ch[$i], CURLOPT_POST, FALSE);
curl_setopt($ch[$i], CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, TRUE);
}
// Initialize the multiple cURL handle
$mh = curl_multi_init();
// Add the handles to the curl_multi handle
for($i = 0; $i < $count; $i++) {
curl_multi_add_handle($mh, $ch[$i]);
}
$running = null;
// Execute the handles
do {
curl_multi_exec($mh, $running);
} while ($running > 0);
$responses = array();
// Remove the handles and return the response
for($i = 0; $i < $count; $i++) {
curl_multi_remove_handle($mh, $ch[$i]);
$responses[$i] = curl_multi_getcontent($ch[$i]);
}
// Close the multiple cURL handle
curl_multi_close($mh);
return $responses;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
手册肯定表明这是一个并行操作:
这里有一个很好的教程。
The manual certainly suggests it's a parallel operation:
There's a good tutorial here.