cURL multi打开的套接字太多



我使用cURL多从一些网站获取数据。代码:

function getURL($ids)
{
    global $mh;
    $curl = array();
    $response = array();
    $n = count($ids);
    for($i = 0; $i < $n; $i++) {
        $id = $ids[$i];
        $url = 'http://www.domain.com/?id='.$id;
        // Init cURL
        $curl[$i] = curl_init($url);
        curl_setopt($curl[$i], CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl[$i], CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($curl[$i], CURLOPT_USERAGENT, 'Googlebot/2.1 (http://www.googlebot.com/bot.html)');
        //curl_setopt($curl[$i], CURLOPT_FORBID_REUSE, true);
        //curl_setopt($curl[$i], CURLOPT_HEADER, false);
        curl_setopt($curl[$i], CURLOPT_HTTPHEADER, array(
            'Connection: Keep-Alive',
            'Keep-Alive: 300'
        ));
        // Set to multi cURL
        curl_multi_add_handle($mh, $curl[$i]);
    }
    // Execute 
    do {
        curl_multi_exec($mh, $flag);
    } while ($flag > 0);
    // Get response
    for($i = 1; $i < $n; $i++) {
        // Get data
        $id = $ids[$i];
        $response[] = array(
            'id' => $id,
            'data' => curl_multi_getcontent($curl[$i])
        );
        // Remove handle
        //curl_multi_remove_handle($mh, $curl[$i]);
    }
    // Reponse
    return $response;
}

但是,我有问题是cURL打开太多的套接字连接到web服务器。每次连接,cURL创建新的套接字到web服务器。我想要当前连接为下一个连接保持活动。我不想要100个URL那么cURL必须创建100个套接字来处理:(

请帮帮我。非常感谢!

所以不要打开那么多套接字。修改代码,只打开X个套接字,然后重复使用这些套接字,直到所有的$ids都被消耗掉。

我知道,这是古老的,但正确的答案还没有给出,恕我直言。

请查看curlmpt_max_total_connections选项,它应该可以解决您的问题:

https://curl.se/libcurl/c/CURLMOPT_MAX_TOTAL_CONNECTIONS.html

还要确保,通过HTTP/2的多路复用不会被意外禁用:

https://curl.se/libcurl/c/CURLMOPT_PIPELINING.html

cURL不再支持经典的HTTP/1管道,但是cURL仍然可以重用现有的HTTP/1连接来发送新请求,一旦当前请求在该连接上完成。

最新更新