为什么 Guzzle 的并发请求功能没有更快?

Why isn't Guzzle's concurrent request feature faster?

我正在尝试使用 Guzzle 的并发请求功能来加速脚本,但是我使用的两个脚本似乎花费了相同的时间。

我有两个 php 脚本,它们只是从用户的 Instagram 帐户中提取最后 100 post 秒,目的是获取每个 post 的嵌入代码。 Instagram 对每个请求有 20 posts 的限制,因此它会循环 5 次。 Instagram 也使用 oembed,所以一旦我拉出每个 post url,我必须将它发送到他们的 oembed 端点以接收回适当的 html。

在原始脚本中,不使用并发请求,它拉取 100 post urls 然后循环请求 oembed 数据。

public function getinstagramPosts2($instagram_id,$token)
{
    $url = 'https://api.instagram.com/v1/users/' . $instagram_id . '/media/recent/';

    $urlparams = [
        'access_token' => $token,
    ];

    $count = 0;

    for($i=1 ; $i<6; $i++)
    {
        $response = $this->getURLResponse($url, $urlparams);

        foreach ($response['data'] as $instapost)
        {
            $url = 'http://api.instagram.com/publicapi/oembed/?url=' . $instapost['link'];

            $embedresponse = $this->getURLResponse($url);

            $posts[$count]['html'] = $embedresponse['html'];

            $count++;

        }
        if(isset($response['pagination']['next_url']))
        {
            $url = $response['pagination']['next_url'];
        }else
        {
            break;
        }
    }

    return $posts;
}

在第二个脚本中,它提取 100 个 post,然后使用 Guzzle 的并发请求功能来加载嵌入请求并 运行 它们并行。

public function getinstagramPosts($instagram_id,$token)
{
    $url = 'https://api.instagram.com/v1/users/' . $instagram_id . '/media/recent/';

    $urlparams = [
        'access_token' => $token,
    ];

    $count = 0;

    for($i=1 ; $i<6; $i++)
    {
        $response = $this->getURLResponse($url, $urlparams);

        foreach ($response['data'] as $instapost)
        {

            $url = 'http://api.instagram.com/publicapi/oembed/?url=' . $instapost['link'];

            $promises[$count] = $this->getHttpClient()->getAsync($url);

            $count++;

        }
        if(isset($response['pagination']['next_url']))
        {
            $url = $response['pagination']['next_url'];
        }else
        {
            break;
        }
    }

    $results = Promise\unwrap($promises);

    $count = 0;

    foreach($results as $result)
    {

        $body = json_decode($result->getBody(),true);

        $posts[$count]['html'] = $body['html'];

        $count++;
    }

    return $posts;

}

我认为这会大大减少时间,但它与原始脚本花费的时间相同。为什么会这样?我错过了什么?感谢您的帮助。

我认为缺少时间差异的主要原因与您处理响应的方式有关。在第一个示例中,您的请求和响应是按顺序执行的。执行请求,接收响应,处理它。在第二个示例中,您执行请求,等待所有响应,然后按顺序处理响应。假设响应的处理是相同的,您唯一的时间差异将是异步执行请求的结果。

话虽如此,使用 GuzzleHttp\Pool 可能会看到更好的结果。我用它取得了很好的效果。您的具体情况可能有所不同。