php使用curl并发减少后端访问时间的方法分析

5年以前  |  阅读数:824 次  |  编程语言:PHP 

本文实例讲述了php使用curl并发减少后端访问时间的方法。分享给大家供大家参考,具体如下:

在我们平时的程序中难免出现同时访问几个接口的情况,平时我们用curl进行访问的时候,一般都是单个、顺序访问,假如有3个接口,每个接口耗时500毫 秒那么我们三个接口就要花费1500毫秒了,这个问题太头疼了严重影响了页面访问速度,有没有可能并发访问来提高速度呢?今天就简单的说一下,利用 curl并发来提高页面访问速度,

1、老的curl访问方式以及耗时统计


    <?php
    function curl_fetch($url, $timeout=3){
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      $data = curl_exec($ch);
      $errno = curl_errno($ch);
      if ($errno>0) {
        $data = false;
      }
      curl_close($ch);
      return $data;
    }
    function microtime_float()
    {
      list($usec, $sec) = explode(" ", microtime());
      return ((float)$usec + (float)$sec);
    }
    $url_arr=array(
       "taobao"=>"http://www.taobao.com",
       "sohu"=>"http://www.sohu.com",
       "sina"=>"http://www.sina.com.cn",
       );
     $time_start = microtime_float();
     $data=array();
     foreach ($url_arr as $key=>$val)
     {
       $data[$key]=curl_fetch($val);
     }
     $time_end = microtime_float();
     $time = $time_end - $time_start;
     echo "耗时:{$time}";
    ?>

耗时:0.614秒

2、curl并发访问方式以及耗时统计


    <?php
    function curl_multi_fetch($urlarr=array()){
      $result=$res=$ch=array();
      $nch = 0;
      $mh = curl_multi_init();
      foreach ($urlarr as $nk => $url) {
        $timeout=2;
        $ch[$nch] = curl_init();
        curl_setopt_array($ch[$nch], array(
        CURLOPT_URL => $url,
        CURLOPT_HEADER => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => $timeout,
        ));
        curl_multi_add_handle($mh, $ch[$nch]);
        ++$nch;
      }
      /* wait for performing request */
      do {
        $mrc = curl_multi_exec($mh, $running);
      } while (CURLM_CALL_MULTI_PERFORM == $mrc);
      while ($running && $mrc == CURLM_OK) {
        // wait for network
        if (curl_multi_select($mh, 0.5) > -1) {
          // pull in new data;
          do {
            $mrc = curl_multi_exec($mh, $running);
          } while (CURLM_CALL_MULTI_PERFORM == $mrc);
        }
      }
      if ($mrc != CURLM_OK) {
        error_log("CURL Data Error");
      }
      /* get data */
      $nch = 0;
      foreach ($urlarr as $moudle=>$node) {
        if (($err = curl_error($ch[$nch])) == '') {
          $res[$nch]=curl_multi_getcontent($ch[$nch]);
          $result[$moudle]=$res[$nch];
        }
        else
        {
          error_log("curl error");
        }
        curl_multi_remove_handle($mh,$ch[$nch]);
        curl_close($ch[$nch]);
        ++$nch;
      }
      curl_multi_close($mh);
      return $result;
    }
    $url_arr=array(
       "taobao"=>"http://www.taobao.com",
       "sohu"=>"http://www.sohu.com",
       "sina"=>"http://www.sina.com.cn",
       );
    function microtime_float()
    {
      list($usec, $sec) = explode(" ", microtime());
      return ((float)$usec + (float)$sec);
    }
    $time_start = microtime_float();
    $data=curl_multi_fetch($url_arr);
    $time_end = microtime_float();
    $time = $time_end - $time_start;
     echo "耗时:{$time}";
    ?>

耗时:0.316秒

帅气吧整个页面访问后端接口的时间节省了一半

3、curl相关参数

curl_close ― Close a cURL session
curl_copy_handle ― Copy a cURL handle along with all of its preferences
curl_errno ― Return the last error number
curl_error ― Return a string containing the last error for the current session
curl_exec ― Perform a cURL session
curl_getinfo ― Get information regarding a specific transfer
curl_init ― Initialize a cURL session
curl_multi_add_handle ― Add a normal cURL handle to a cURL multi handle
curl_multi_close ― Close a set of cURL handles
curl_multi_exec ― Run the sub-connections of the current cURL handle
curl_multi_getcontent ― Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set
curl_multi_info_read ― Get information about the current transfers
curl_multi_init ― Returns a new cURL multi handle
curl_multi_remove_handle ― Remove a multi handle from a set of cURL handles
curl_multi_select ― Wait for activity on any curl_multi connection
curl_setopt_array ― Set multiple options for a cURL transfer
curl_setopt ― Set an option for a cURL transfer
curl_version ― Gets cURL version information

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php curl用法总结》、《PHP数组(Array)操作技巧大全》、《PHP数据结构与算法教程》、《PHP数学运算技巧总结》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

 相关文章:
PHP分页显示制作详细讲解
SSH 登录失败:Host key verification failed
获取IMSI
将二进制数据转为16进制以便显示
获取IMEI
文件下载
贪吃蛇
双位运算符
PHP自定义函数获取搜索引擎来源关键字的方法
Java生成UUID
发送邮件
年的日历图
提取后缀名
在Zeus Web Server中安装PHP语言支持
让你成为最历害的git提交人
Yii2汉字转拼音类的实例代码
再谈PHP中单双引号的区别详解
指定应用ID以获取对应的应用名称
Python 2与Python 3版本和编码的对比
php封装的page分页类完整实例