自己整理下,有时间在研究
class Learncurlmulti_IndexController extends ControllerBase_LCMbase{
private $hosts=array(
'http://my.com/LearnCurlMulti_add',
'http://my.com/LearnCurlMulti_edit',
'http://my.com/LearnCurlMulti_detail',
'http://my.com/LearnCurlMulti_list',
);
/**
* curl单线程请求
* @final 20S
*/
public function indexAction(){
p(date('H:i:s',time()));
$data=array();
foreach ($this->hosts as $v){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$v);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_NOSIGNAL,true);
$data[]=curl_exec($ch);
}
p(date('H:i:s',time()));
p($data);
}
/**
* 传统多线程
* @final 5S
* 缺点,总要等最后一个完成才算全完成,先完成的还在占用资源
*/
public function multiAction(){
p(date('H:i:s',time()));
$queue =curl_multi_init();
$map=array();
foreach($this->hosts as $k=>$url){
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_TIMEOUT,30);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_NOSIGNAL,true);
curl_setopt($ch,CURLOPT_NOSIGNAL,1);
curl_multi_add_handle($queue,$ch);
$map[$url]=$ch;
}
do{
$mrc=curl_multi_exec($queue,$active);
}while($mrc==CURLM_CALL_MULTI_PERFORM);
while($active && $mrc==CURLM_OK){
//这块是防止select返回1导致死循环,判断select前先exec下
while(curl_multi_exec($queue,$active)===CURLM_CALL_MULTI_PERFORM){
$mrc=curl_multi_exec($queue,$active);
}
if(curl_multi_select($queue,0.5)!=-1){
do{
$mrc=curl_multi_exec($queue,$active);
}while($mrc==CURLM_CALL_MULTI_PERFORM);
}
}
$responses=array();
foreach($map as $url=>$c){
$responses[$url]=curl_multi_getcontent($c);
curl_multi_remove_handle($queue,$c);
curl_close($c);
}
curl_multi_close($queue);
p($responses);
p(date('H:i:s',time()));
die;
}
/**
* 改进版多线程
*/
public function rollingmultiAction(){
$queue=curl_multi_init();
$map=array();
foreach($this->hosts as $url){
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_TIMEOUT,1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_NOSIGNAL,true);
curl_multi_add_handle($queue,$ch);
$map[(string)$ch]=$url;
}
$responses=array();
do{
while(($code=curl_multi_exec($queue,$active))==CURLM_CALL_MULTI_PERFORM);
if($code!=CURLM_OK){break;}
while($done=curl_multi_info_read($queue)){
$info=curl_getinfo($done['handle']);
$error=curl_error($done['handle']);
$results=curl_multi_getcontent($done['handle']);
$responses[$map[(string)$done['handle']]]=compact('info','error','results');
curl_multi_remove_handle($queue,$done['handle']);
curl_close($done['handle']);
}
if($active>0){
curl_multi_select($queue,0.5);
}
}while($active);
curl_multi_close($queue);
p($responses);
die;
}
}
网友评论