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

本文介绍了一个用于并发执行多个cURL请求的PHP函数curlMultiRequest()。该函数通过cURL多路复用来提高性能并控制超时,适用于需要同时访问多个远程资源的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[b]为什么这么做?[/b]
目前的接口话的服务调用,为了保证性能和稳定性,我们都会对调用的第三方接口做并发,超时控制。

[b]代码实现(网上找的现成的)[/b]

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;
}

调用方式:

$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);


[b]注意事项[/b]
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);
}


[list]
参考资料:
[*]http://stackoverflow.com/questions/9062798/php-curl-timeout-is-not-working
[*]http://www.laruence.com/2014/01/21/2939.html
[/list]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值