首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Curl中一次访问多个URL

在Curl中一次访问多个URL
EN

Stack Overflow用户
提问于 2019-12-05 09:23:44
回答 1查看 2.2K关注 0票数 2

我正在开发API,在一个请求中返回单一货币记录。一个请求需要0.5秒-1秒的响应,15个请求需要7-15秒.

如我所知,服务器每秒钟可以管理100多个请求。我想在服务器上同时点击15个请求,这样服务器将在1-2秒内给出响应,而不是在15秒内。返回一个数组中的所有数据,以节省加载时间。

检查我的代码

我使用循环,循环等待,直到前面的卷曲请求不完成。我怎么能说循环,保持继续,不等待回应。

代码语言:javascript
复制
$time_Start = microtime(true);

$ids = array(1,2,11,15,20,21); // 6 ids in demo, 15+ ids in real
$response = array();
foreach ($ids as $key => $id) {
    $response[$id] = get_data($id);
}

echo "Time: ". (microtime(true)-$time_Start)."sec";
// output 5 seconds on 6 request


function get_data($id){
    $fcs_api_key = "API_KEY";
    $ch=curl_init();
    curl_setopt($ch,CURLOPT_URL,"https://fcsapi.com/api/forex/indicators?id=".$id."&period=1d&access_key=".$fcs_api_key);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $buffer = curl_exec($ch);
    curl_close($ch);

    return $buffer;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-05 10:30:17

您可以使用PHP https://www.php.net/manual/en/function.curl-multi-init.php

下面我编写了一个打开并行请求的代码。

代码语言:javascript
复制
$time_Start = microtime(true);

$ids = array(1,2,3,4,5,6); // You forex currency ids.
$response = php_curl_multi($ids);

echo "Time: ". (microtime(true)-$time_Start)."sec";
// Time: 0.7 sec

函数

代码语言:javascript
复制
function php_curl_multi($ids){
    $parameters = "/api/forex/indicators?period=1d&access_key=API_KEY&id="; // ID will set dynamic
    $url        = "https://fcsapi.com".$parameters;

    $ch_index = array(); // store all curl init
    $response = array();

    // create both cURL resources
    foreach ($ids as $key => $id) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,  $url.$id);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $ch_index[] = $ch;
    }

    //create the multiple cURL handle
    $mh = curl_multi_init();

    //add the handles
    foreach ($ch_index as $key => $ch) {
        curl_multi_add_handle($mh,$ch);
    }

    //execute the multi handle
    do {
        $status = curl_multi_exec($mh, $active);
        if ($active) {
            curl_multi_select($mh);
        }
    } while ($active && $status == CURLM_OK);

    //close the handles
    foreach ($ch_index as $key => $ch) {
        curl_multi_remove_handle($mh, $ch);
    }
    curl_multi_close($mh);


    // get all response
    foreach ($ch_index as $key => $ch) {
        $response[] = curl_multi_getcontent($ch);
    }

    return $response;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59191866

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档