在我们平时的程序中难免出现同时访问几个接口的情况,平时我们用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. JS之script标签

    1.script标签的位置 script标签可以在head标签中,也可以在body标签中 2.async属性 async的目的是不让页面等待js文件的下载和执行,从而异步加载页面中的其他内容.只支持外 ...

  2. sql server 2008语句中的go有什么用?

    GO表示一个批处理的结束, SQLSERVER遇到Go以后就会将GO之前的语句作为一整批进行处理你在SSMS里执行的时候, 通常加不加都可以,但是如果实在SQLCMD下执行, GO就是一个执行命令了另 ...

  3. Java学习-036-JavaWeb_005 -- JSP 动作标识 - forward

    JSP 动作主要作用是根据指定的动作进行相应的处理. 一.param 动作 用来给 HTML 文件和 JSP 文件传递参数的,经常和 forward.include.plugin 动作结合使用,语法格 ...

  4. Asp.net MVC 批量删除数据

    ProductList视图 <div class="mid"> <div id="editInfo"> @using (Html.Beg ...

  5. sell-- 英文网站产品显示404?

    1. 简介: 通过在主页(header.jsp)查询B22212,在localhost本地, cn和us查询的结果search.jsp中显示都是没有找到! 但是在外网(www),cn能够查询到,并展示 ...

  6. SQL语句里怎么获得当前年份(MySQL数据库)

    使用函数Year及CurDate的组合: Year(CurDate()) select date_format(min(date),'%Y-%m-%d') as mindate, date_forma ...

  7. TermServDevices报错导致服务器死机(远程服务使用者必读)

    事件类型: 错误 事件来源: TermServDevices 事件 ID: 1111 描述:打印机 !!192.168.99.6!HP LaserJet 3050 Series PCL 5e 所需的驱 ...

  8. iOS单例模式

    单例模式用于当一个类只能有一个实例的时候, 通常情况下这个“单例”代表的是某一个物理设备比如打印机,或是某种不可以有多个实例同时存在的虚拟资源或是系统属性比如一个程序的某个引擎或是数据.用单例模式加以 ...

  9. js引入img标签和图片

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  10. ionic一些常见问题及方法

    1.打包的app无法访问互联网及网络资源(比如网页调试可以请求数据,安装到手机上无法请求数据) 添加白名单插件 ionic plugin add https://github.com/apache/c ...