doz59484 2016-03-10 16:36
浏览 36

如何使用curl multi异步调用api

I have been facing this problem that i have 4 apis to process and get output to final web page. When i does this my web page loading time is more than one minute. After long thinking i figured out that i was calling then synchronously. I need to call then asynchronously to avoid lag. Then i ended up with the code here which isn't returning any data on web page . Help me out! . I got this code from http://php.net/manual/en/function.curl-multi-exec.php

    // set URL and other appropriate options
    curl_setopt($ch1, CURLOPT_URL, "http://example1.com");
    curl_setopt($ch1, CURLOPT_POST, 1);
    curl_setopt($ch1, CURLOPT_POSTFIELDS,"x=a&y=b");
    curl_setopt($ch1, CURLOPT_HEADER, 0);
    curl_setopt($ch2, CURLOPT_URL, "http://www.example2.com"."m=c&n=d");
    curl_setopt($ch2, CURLOPT_HEADER, 0);
    curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);

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

    //add the two handles
    curl_multi_add_handle($mh,$ch1);
    curl_multi_add_handle($mh,$ch2);

    $active = null;
    //execute the handles
    do {
        $mrc = curl_multi_exec($mh, $active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);

    while ($active && $mrc == CURLM_OK) {
        if (curl_multi_select($mh) != -1) {
            do {
                $mrc = curl_multi_exec($mh, $active);
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);
        }
    }

    //close the handles
    curl_multi_remove_handle($mh, $ch1);
    curl_multi_remove_handle($mh, $ch2);
    curl_multi_close($mh);

        echo $mrc;


    ?>

I have 4 apis , of which 2 are POST requests and 2 are GET. Thanks in advance

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 WPF 大屏看板表格背景图片设置
    • ¥15 这个主板怎么能扩出一两个sata口
    • ¥15 不是,这到底错哪儿了😭
    • ¥15 2020长安杯与连接网探
    • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
    • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
    • ¥16 mybatis的代理对象无法通过@Autowired装填
    • ¥15 可见光定位matlab仿真
    • ¥15 arduino 四自由度机械臂
    • ¥15 wordpress 产品图片 GIF 没法显示