zoukankan      html  css  js  c++  java
  • 自己封装的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;
  • 相关阅读:
    hive之窗口函数
    linux环境下Mysql的卸载和重新安装和启动
    2017ACM暑期多校联合训练
    2017ACM暑期多校联合训练
    状态压缩dp
    铺砖问题 (状态压缩dp)
    POj 2104 K-th Number (分桶法+线段树)
    POJ 2991 Crane (线段树)
    4 Values whose Sum is 0 POJ 2785 (折半枚举)
    Billboard HDU 2795 (线段树)
  • 原文地址:https://www.cnblogs.com/guangxiaoluo/p/3336916.html
Copyright © 2011-2022 走看看