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


Posted in PHP onMay 12, 2016

本文实例讲述了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 相关文章推荐
一个php作的文本留言本的例子(二)
Oct 09 PHP
文件上传程序的全部源码
Oct 09 PHP
如何写php程序?
Dec 08 PHP
php smarty模版引擎中变量操作符及使用方法
Dec 11 PHP
smarty内置函数capture用法分析
Jan 22 PHP
PHP实现的简单分页类及用法示例
May 06 PHP
既简单又安全的PHP验证码 附调用方法
Jun 02 PHP
CakePHP框架Model函数定义方法示例
Aug 04 PHP
PHP测试框架PHPUnit组织测试操作示例
May 28 PHP
PHP+MySQL实现模糊查询员工信息功能示例
Jun 01 PHP
PHP html_entity_decode()函数讲解
Feb 25 PHP
php+ajax实现商品对比功能示例
Apr 13 PHP
php反射类ReflectionClass用法分析
May 12 #PHP
PHP 的比较运算与逻辑运算详解
May 12 #PHP
php使用文本统计访问量的方法
May 12 #PHP
php格式化json函数示例代码
May 12 #PHP
php ucwords() 函数将字符串中每个单词的首字符转换为大写(实现代码)
May 12 #PHP
yii2带搜索功能的下拉框实例详解
May 12 #PHP
使用php从身份证号中获取一系列线索(星座、生肖、生日等)
May 11 #PHP
You might like
php 数组动态添加实现代码(最土团购系统的价格排序)
2011/12/30 PHP
PHP多线程批量采集下载美女图片的实现代码(续)
2013/06/03 PHP
解析用PHP实现var_export的详细介绍
2013/06/20 PHP
ThinkPHP3.2.2的插件控制器功能简述
2014/07/09 PHP
PHP Yaf框架的简单安装使用教程(推荐)
2016/06/08 PHP
PHP SFTP实现上传下载功能
2017/07/26 PHP
ubutu 16.04环境下,PHP与mysql数据库,网页登录验证实例讲解
2017/07/20 PHP
PHP按符号截取字符串的指定部分的实现方法
2018/09/10 PHP
Yii框架使用PHPExcel导出Excel文件的方法分析【改进版】
2019/07/24 PHP
JS随即打乱数组实现代码
2012/12/03 Javascript
jQuery实现限制textarea文本框输入字符数量的方法
2015/05/28 Javascript
超漂亮的jQuery图片轮播特效
2015/11/24 Javascript
JavaScript实现点击按钮字体放大、缩小
2016/02/29 Javascript
原生js实现autocomplete插件
2016/04/14 Javascript
jQuery Easyui 验证两次密码输入是否相等
2016/05/13 Javascript
js弹出窗口返回值的简单实例
2016/05/28 Javascript
Javascript中构造函数要注意的一些坑
2017/01/23 Javascript
Bootstrap表格使用方法详解
2017/02/17 Javascript
jquery validate 实现动态增加/删除验证规则操作示例
2019/10/28 jQuery
koa2 数据api中间件设计模型的实现方法
2020/07/13 Javascript
[40:50]2014 DOTA2国际邀请赛中国区预选赛 5 23 CIS VS LGD第四场
2014/05/24 DOTA
在Linux下调试Python代码的各种方法
2015/04/17 Python
Python协程的用法和例子详解
2017/09/09 Python
详解python之协程gevent模块
2018/06/14 Python
python笔记_将循环内容在一行输出的方法
2019/08/08 Python
Python facenet进行人脸识别测试过程解析
2019/08/16 Python
关于探究python中sys.argv时遇到的问题详解
2021/02/23 Python
澳大利亚汽车零部件、音响及配件超市:Automotive Superstore
2018/06/19 全球购物
生态学毕业生自荐信
2013/10/27 职场文书
蜜蜂引路教学反思
2014/02/04 职场文书
光信息科学与技术专业职业生涯规划
2014/03/13 职场文书
对外汉语专业大学生职业生涯规划书
2014/10/11 职场文书
用python删除文件夹中的重复图片(图片去重)
2021/05/12 Python
vue项目多环境配置(.env)的实现
2021/07/21 Vue.js
《模拟人生4》推出新补丁 “婚礼奇缘”DLC终于得到修复
2022/04/03 其他游戏
mysql数据库如何转移到oracle
2022/12/24 MySQL