自己封装的php Curl并发处理,欢迎提出问题优化。

因为项目需要,发现一个一个发送请求实在太慢,无奈之下,我们可以封装一个并发处理的curl请求批处理句柄来减少重复创建句柄的问题

代码如下:

/*
 *@param array $data url的参数
 *@param  string $url  url地址
 *@return array $retsult  结果序列
*/
function getmulti($data,$url){
//组合url参数
$ch = array();
$mh = curl_multi_init();
$result = array();
foreach ($data as $k => $v) {
    $query[$k] = http_build_query($v);
    $ch[$k] = curl_init();
    $options = array(
        CURLOPT_URL=> $url.'?'.$query[$k],
        CURLOPT_TIMEOUT => 50,
        CURLOPT_HEADER => 0,
        CURLOPT_RETURNTRANSFER => TRUE,
);
curl_setopt_array($ch[$k], $options);
  
curl_multi_add_handle($mh,$ch[$k]);
}
$active = null;
// 执行批处理句柄
do {
   $mrc = curl_multi_exec($mh, $active);
} while ($active > 0);
foreach ($ch as $ck => $cv) {
    $result[] = curl_multi_getcontent($cv);
    usleep(1);
    curl_multi_remove_handle($mh, $cv);
}
  
curl_multi_close($mh);
  
//echo $options[CURLOPT_URL];die();
  
return $result;
}
//example:
$data = array(
                'happy'=>array('emotion'=>'happy', 'tag'=>'男人'),   
                'anger'=>array('emotion'=>'anger', 'tag'=>'男人'),   
                'sad'=>array('emotion'=>'sad', 'tag'=>'男人'),   
                'fear'=>array('emotion'=>'fear', 'tag'=>'男人'), 
                'surprise'=>array('emotion'=>'surprise', 'tag'=>'男人'), 
                'none'=>array('emotion'=>'none', 'tag'=>'男人'),
        );
        $newdata = array();
        $hotres = '';
        $url = 'http://www.xxx.com/demo/getEmotionDetails.jsp';
        $startime = time().'<br />';
        echo '开始时间:'.$startime;
        foreach ($data as $k=>$v){
            //$hotres = $this->get($data, $url);
            //$hotres = $this->get($v, $url);
            $hotres = file_get_contents($url.'?'.http_build_query($v));
            //$newdata[] = object_to_array(json_decode($hotres));
            $newdata[] = $hotres;
        }
        /*      foreach ($hotres as $hk=>$hv){
         $newdata[$data[$hk]['emotion']] = object_to_array(json_decode($hv));
        } */
        echo '消耗时间:'.(time()-$startime).'<br />';
        echo '结束时间:'.time().'<br />';
  
        echo '<pre>';print_r($newdata);exit;

 

posted @ 2013-09-24 14:58  老骆  阅读(707)  评论(0编辑  收藏  举报