如何加快php中的cURL速度?

问题描述 投票:0回答:8

我正在尝试从 Twitter 获取嵌入推文。所以,我使用 cURL 来取回 json。我写了一个小测试,但测试需要大约 5 秒,就像我在本地运行时一样。所以,我不确定我在这里做错了什么。

public function get_tweet_embed($tw_id) {

    $json_url = "https://api.twitter.com/1/statuses/oembed.json?id={$tw_id}&align=left&omit_script=true&hide_media=false";

    $ch = curl_init( $json_url );
    $start_time = microtime(TRUE);
    $JSON = curl_exec($ch);
    $end_time = microtime(TRUE);
    echo $end_time - $start_time; //5.7961111068726

    return $this->get_html($JSON);
}

private function get_html($embed_json) {
    $JSON_Data = json_decode($embed_json,true);
    $tw_embed_code = $JSON_Data["html"];
    return $tw_embed_code;
}

当我粘贴链接并从浏览器中测试它时,速度非常快。

php rest twitter
8个回答
31
投票

我所经历过的最好的加速是重复使用相同的卷曲手柄。 将

$ch = curl_init( $json_url );
替换为
curl_setopt($ch, CURLOPT_URL, $url);
。然后函数外面有一个
$ch = curl_init();
。您需要在函数中将
$ch
设置为全局才能访问它。

重复使用curl句柄可以保持与服务器的连接打开。仅当请求之间的服务器与您的服务器相同时,这才有效。


21
投票

最终的加速解决方案是这样的

curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );

问候


10
投票

尝试设置

curl_setopt($ch, CURLOPT_ENCODING,  '')
它启用 gzip 压缩


7
投票

为了加快 cURL 速度,我建议为 API 创建特殊类(例如

ApiClient
)并使用一个共享 cURL 处理程序,仅更改每个请求的 URL。还要切断名称解析请求并使用 gzip 响应。

我每天需要从一台 API 服务器处理大约 100 万个实体,这限制了我们只能使用一个并发连接。我创建了那个类。我希望它能帮助其他人优化他们的curl请求。

class ApiClient
{
    const CURL_TIMEOUT = 3600;
    const CONNECT_TIMEOUT = 30;
    const HOST = 'api.example.com';
    const API_TOKEN = 'token';

    /** @var resource CURL handler. Reused every time for optimization purposes */
    private $ch;
    /** @var string URL for API. Calculated at creating object for optimization purposes */
    private $url;

    public function __construct()
    {
        $this->url = 'https://' . self::HOST . '/v1/entity/view?token=' . self::API_TOKEN . '&id=';
                                // Micro-optimization: every concat operation takes several milliseconds
                                // But for millions sequential requests it can save a few seconds
        $host = [implode(':', [ // $host stores information for domain names resolving (like /etc/hosts file)
            self::HOST, // Host that will be stored in our "DNS-cache"
            443, // Default port for HTTPS, can be 80 for HTTP
            gethostbyname(self::HOST), // IPv4-address where to point our domain name (Host)
        ])];
        $this->ch = curl_init();
        curl_setopt($this->ch, CURLOPT_ENCODING, '');  // This will use server's gzip (compress data)
                                                       // Depends on server. On some servers can not work
        curl_setopt($this->ch, CURLOPT_RESOLVE, $host); // This will cut all requests for domain name resolving
        curl_setopt($this->ch, CURLOPT_TIMEOUT, self::CURL_TIMEOUT); // To not wait extra time if we know
                                                            // that api-call cannot be longer than CURL_TIMEOUT
        curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, self::CONNECT_TIMEOUT); // Close connection if server doesn't response after CONNECT_TIMEOUT
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true); // To return output in `curl_exec`
    }

    /** @throws \Exception */
    public function requestEntity($id)
    {
        $url = $this->url . $id;

        curl_setopt($this->ch, CURLOPT_URL, $url);

        $data = curl_exec($this->ch);

        if (curl_error($this->ch)) {
            throw new \Exception('cURL error (' . curl_errno($this->ch) . '): ' . curl_error($this->ch));
        }

        return $data;
    }

    public function __destruct()
    {
        curl_close($this->ch);
    }
}

此外,如果您没有与服务器只有一个连接的限制,则可以使用

curl_multi_*
功能。


6
投票

关于环境,我在 PHP 中观察到,cURL 在大多数环境中通常运行得非常快,除了 CPU 较低且网络性能较慢的地方。例如,在我的 MAMP 安装的本地主机上,curl 很快,在较大的亚马逊实例上,curl 很快。但在小型蹩脚主机上,我发现它存在性能问题,连接速度明显较慢。不过,我不确定为什么速度较慢。而且,它肯定没有慢 5 秒。

为了帮助确定它是 PHP 还是您的环境,您应该尝试通过命令行与curl 交互。如果仍然是 5 秒,至少您可以排除 PHP 代码的问题。


5
投票

尝试

CURLOPT_TCP_FASTOPEN => 1

...激活 TCP-Fast-Open。

已添加到 cURL 7.49.0,添加到 PHP 7.0.7。


2
投票

尝试与

--ipv4
参数一起使用。

这将强制curl仅使用ipv-4并忽略ipv-6,它仍然与某些设备不太兼容并减慢了进程。在我的 curl 命令中添加

--ipv4
将成本从 8 秒减少到 4 秒。速度快了 %50。


0
投票

也不要忘记添加这个:

CURLOPT_ENCODING  =>  'gzip,deflate'
© www.soinside.com 2019 - 2024. All rights reserved.