Home > Backend Development > PHP Tutorial > 关于php curl支持并发请求,并毫秒统制超时

关于php curl支持并发请求,并毫秒统制超时

WBOY
Release: 2016-06-13 12:09:23
Original
1363 people have browsed it

关于php curl支持并发请求,并毫秒控制超时
为什么这么做?
目前的接口话的服务调用,为了保证性能和稳定性,我们都会对调用的第三方接口做并发,超时控制。

代码实现(网上找的现成的)

public static function curlMultiRequest($urls, $options = array()) {        $ch= array();        $results = array();        $mh = curl_multi_init();        foreach($urls as $key => $val) {            $ch[$key] = curl_init();            if ($options) {                curl_setopt_array($ch[$key], $options);            }            curl_setopt($ch[$key], CURLOPT_URL, $val);            curl_multi_add_handle($mh, $ch[$key]);        }        $running = null;        do {            curl_multi_exec($mh, $running);        } while ($running > 0);        // Get content and remove handles.        foreach ($ch as $key => $val) {            $results[$key] = curl_multi_getcontent($val);            curl_multi_remove_handle($mh, $val);        }        curl_multi_close($mh);        return $results;    }
Copy after login

调用方式:
$urls = [     'http://www.baidu.com',     'http://www.qq.com'      ];$opts = [  CURLOPT_HEADER => false,  CURLOPT_TIMEOUT_MS => 50,//执行脚本超时  //CURLOPT_CONNECTTIMEOUT_MS => 50,//网络选址超时  CURLOPT_RETURNTRANSFER => true,  CURLOPT_NOSIGNAL => true, //这个是设定毫秒必须设定];curlMultiRequest($urls,$opts);
Copy after login


注意事项
1.支持毫秒 cURL 7.16.2中被加入。从PHP 5.2.3起可使用
2.CURLOPT_TIMEOUT_MS,CURLOPT_CONNECTTIMEOUT_MS 未定义时
if (!defined('CURLOPT_CONNECTTIMEOUT_MS')) {    define('CURLOPT_CONNECTTIMEOUT_MS', 156);}if (!defined('CURLOPT_TIMEOUT_MS')) {    define('CURLOPT_TIMEOUT_MS', 155);}
Copy after login



    参考资料:
  • http://stackoverflow.com/questions/9062798/php-curl-timeout-is-not-working
  • http://www.laruence.com/2014/01/21/2939.html
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template