为什么Guzzle的并发请求功能不会更快?

时间:2015-10-15 20:20:46

标签: php concurrency httprequest guzzle

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

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

在原始脚本中,不使用并发请求,它会提取100个帖子网址,然后循环请求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个帖子,然后使用Guzzle的并发请求功能来加载oembed请求并并行运行它们。

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;

}

我认为这会显着减少时间,但它需要与原始脚本相同的时间。那为什么会这样?我错过了什么?谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

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

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

相关问题