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

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

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}";
?>
输出结果array('taobao'=>result,'sina'=>result,'baidu'=>result)  ;
耗时:0.316秒
3、curl相关参数
来自:http://cn2.php.net/manual/en/ref.curl.php
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

利用curl并发来提高页面访问速度的更多相关文章

  1. 萧墙HTML5手机发展之路(51)——jquerymobile在提高页面访问速度

    正在使用jQuery Mobile开发时间可以选择单页模板和多页模板,在单页模板时从一个页面跳转到另一个页面时从需要server要求.用户会感到轻微的停顿. 使用多页模板,为了改善网页之间跳跃的流畅, ...

  2. 巧用linux服务器的/dev/shm/,如果合理使用,可以避开磁盘IO不给力,提高网站访问速度。

    巧用linux服务器的/dev/shm/ 巧用linux服务器的/dev/shm/,如果合理使用,可以避开磁盘IO不给力,提高网站访问速度. 首先让我们认识一下,什么是tmpfs和/dev/shm/? ...

  3. Javascript高性能编程-提高数据访问速度

         hasOwnProperty()仅检索实例不检索原型,in即检索实例,又检索原型      成员嵌套越深,访问速度越慢,只在必要的情况下使用对象成员.      如果在同一个函数中你要多次读 ...

  4. 超简单!教你如何修改源列表(sources.list)来提高软件访问速度

    因为Ubuntu官方的源地址不在国内,所以在国内的访问速度非常慢,比如:我们要下载或是更新软件那速度比蜗牛还慢.所以,我们需要改成国内的镜像服务器,这样,我们在下载或更新软件的时候就会很快了. 配置步 ...

  5. Javascript高性能编程-提高Dom访问速度

    在浏览器中对于Dom的操作和普通的脚本的操作处于两个不同的dll中,两个dll的交互是比较耗时的,优化对Dom的操作可以提高脚本的执行速度.下面是对如何优化的一些总结: 将需要多次操作的节点存储在一个 ...

  6. 使用Gzip压缩数据,加快页面访问速度

                 在返回的json数据量大时,启用Gzip压缩,可以提高传输效率.下面为Gzip压缩对json字符串压缩并输出到页面的代码. 一.代码 /** 向浏览器输出字符串响应数据,启用 ...

  7. 小强的HTML5移动开发之路(51)——jquerymobile中改善页面访问速度

    在使用jQuery Mobile进行开发的时候可以选择单页模版和多页模版,在使用单页模版的时候从一个页面跳转到另一个页面的时候需要从服务器请求,用户会感到略有停顿.使用多页模版,可以改善页面跳转之间的 ...

  8. Google Font字体本地化使用提高网站访问速度

    Google Web font在国内经常不稳定,速度在国内延迟也很高,而引发网页打开速度慢. 一.常见的字体格式介绍 不同的浏览器对字体格式支持是不一致的,常见的如下: 1.TureTpe(.ttf) ...

  9. 利用curl抓取远程页面内容

    最基本的操作如下 $curlPost = 'a=1&b=2';//模拟POST数据$cookie_file    =    tempnam('./temp','kie');//可选,保存ses ...

随机推荐

  1. 创建podSpec,使用pod管理第三方库

    提要: podfile文件会先读取.podspec文件,根据.podspec文件的指向来下载第三方库到项目中. 本文先通过一.二.三项,这三个步骤讲解了如何建立一个.podspec文件在本地.coco ...

  2. oracle 变量声明 初始化 赋值

    DECLARE sname VARCHAR2(20); BEGIN sname:='xxx'; sname:=sname||' and tom'; dbms_output.put_line(sname ...

  3. http和网页设计

    .基本概念: CGI(Common Gate Interface,通用网关接口) HTML均是静态网页,它无法实现一些复杂的功能,而CGI可以为我们实现. get方式提交表单: 当表单被发送到服务器断 ...

  4. cname和CDN

    http://blog.csdn.net/crazw/article/details/8986504 先说一下DNS的几个基本概念: 一. 根域 就是所谓的“.”,其实我们的网址www.baidu.c ...

  5. openni2 和opencv读取数据

    http://blog.csdn.net/aptx704610875/article/details/49585241

  6. linux多个python版本下导致no request报错

    解决办法: sudo apt-get install uwsgi uwsgi-core uwsgi-plugin-python sudo apt-get install uwsgi-plugin-py ...

  7. 分享一下怎么开发一款图片视频类App,秒拍和prisma

    第一步,分解短视频App的功能 我们在秒拍官网看到如此描述: [视频拍摄及导入]支持直接拍摄及导入手机本地的视频 [照片电影]照片专属特效,轻松创作照片电影 [MV特效]10余款全新MV特效,让普通视 ...

  8. PHP中用下划线开头的变量含义

    http://blog.csdn.net/zlking02/article/details/6752256 一个下划线是私有变量以及私有方法两个下划线是PHP内置变量. https://segment ...

  9. kafka系列教程2(设计构造及原理1)

    kafka采用了一些非主流(unconventional)并经过实践的设计使其高效和可扩展.在实际使用中kafka显示出了相对于常见流行的消息系统的优越性.并且每天能够处理上百GB的新的数据.   类 ...

  10. Python_01 在DOS环境运行python程序

    >怎么在DOS环境运行一个python程序 >>在文本编辑器中编辑程序,最后保存成   文件名.py  的格式 >>在DOS界面下找到源程序所在的路径,然后用  pyth ...