之前写了个监测的脚本,利用curl的多线程方式来读取,结果导致CPU占用过高,经过查找,找到可以降低CPU负载的方法,如下:
/**
* cURL multi批量处理
*
* @author mckee
* @link http://www.phpddt.com
*
*/
$url_array = array(
'http://www.phpddt.com/',
'http://www.phpddt.com/php/627.html',
'http://www.phpddt.com/php/258.html'
);
$handles = $contents = array();
//初始化curl multi对象
$mh = curl_multi_init();
//添加curl 批处理会话
foreach($url_array as $key => $url){
$handles[$key] = curl_init($url);
curl_setopt($handles[$key], CURLOPT_SSL_VERIFYPEER, false); //https支持
curl_setopt($handles[$key], CURLOPT_SSL_VERIFYHOST, false); //https支持
curl_setopt($handles[$key], CURLOPT_RETURNTRANSFER, 1);
curl_setopt($handles[$key], CURLOPT_TIMEOUT, 10);
curl_multi_add_handle($mh, $handles[$key]);
}
//======================执行批处理句柄=================================
$active = null;
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active and $mrc == CURLM_OK) {
if(curl_multi_select($mh) === -1){
usleep(100);
}
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
//====================================================================
//获取批处理内容
foreach($handles as $i => $ch){
$content = curl_multi_getcontent($ch);
$contents[$i] = curl_errno($ch) == 0 ? $content : '';
}
//移除批处理句柄
foreach($handles as $ch){
curl_multi_remove_handle($mh, $ch);
}
//关闭批处理句柄
curl_multi_close($mh);
print_r($contents);
上面这段程序重点是执行批处理的那段,普通的处理:
do { $n=curl_multi_exec($mh,$active); } while ($active);
会造成CPU Loading过高,因为$active要等全部url数据接受完毕才变成false,所以这里用到了curl_multi_exec的返回值判断是否还有数据,当有数据的时候就不停调用curl_multi_exec,没有执行数据就会sleep,如此就会避免CPU Loading 100%了。