这次给大家带来使用curl_multi实现并发请求步骤分析,使用curl_multi实现并发请求的注意事项有哪些,下面就是实战案例,一起来看一下。
class curlmultiutil {
/**
* 根据url,postdata获取curl请求对象,这个比较简单,可以看官方文档
*/
private static function getcurlobject($url,$postdata=array(),$header=array()){
$options = array();
$url = trim($url);
$options[curlopt_url] = $url;
$options[curlopt_timeout] = 3;
$options[curlopt_returntransfer] = true;
foreach($header as $key=>$value){
$options[$key] =$value;
}
if(!empty($postdata) && is_array($postdata)){
$options[curlopt_post] = true;
$options[curlopt_postfields] = http_build_query($postdata);
}
if(stripos($url,'https') === 0){
$options[curlopt_ssl_verifypeer] = false;
}
$ch = curl_init();
curl_setopt_array($ch,$options);
return $ch;
}
/**
* [request description]
* @param [type] $chlist
* @return [type]
*/
private static function request($chlist){
$downloader = curl_multi_init();
// 将三个待请求对象放入下载器中
foreach ($chlist as $ch){
curl_multi_add_handle($downloader,$ch);
}
$res = array();
// 轮询
do {
while (($execrun = curl_multi_exec($downloader, $running)) == curlm_call_multi_perform);
if ($execrun != curlm_ok) {
break;
}
// 一旦有一个请求完成,找出来,处理,因为curl底层是select,所以最大受限于1024
while ($done = curl_multi_info_read($downloader)){
// 从请求中获取信息、内容、错误
// $info = curl_getinfo($done['handle']);
$output = curl_multi_getcontent($done['handle']);
// $error = curl_error($done['handle']);
$res[] = $output;
// 把请求已经完成了得 curl handle 删除
curl_multi_remove_handle($downloader, $done['handle']);
}
// 当没有数据的时候进行堵塞,把 cpu 使用权交出来,避免上面 do 死循环空跑数据导致 cpu 100%
if ($running) {
$rel = curl_multi_select($downloader, 1);
if($rel == -1){
usleep(1000);
}
}
if($running == false){
break;
}
}while(true);
curl_multi_close($downloader);
return $res;
}
/**
* [get description]
* @param [type] $urlarr
* @return [type]
*/
public static function get($urlarr){
$data = array();
if (!empty($urlarr)) {
$chlist = array();
foreach ($urlarr as $key => $url) {
$chlist[] = self::getcurlobject($url);
}
$data = self::request($chlist);
}
return $data;
}
}
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
php使用file_get_contents发送http请求步骤详解
php通过strace定位排解故障位置并解决
以上就是使用curl_multi实现并发请求步骤分析的详细内容。