【问题标题】:Why isn't Guzzle's concurrent request feature faster?为什么 Guzzle 的并发请求功能没有更快?
【发布时间】:2015-10-19 02:54:21
【问题描述】:

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

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

在原始脚本中,不使用并发请求,它拉取 100 个帖子 url,然后循环请求 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;

}

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

【问题讨论】:

    标签: php concurrency httprequest guzzle


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-09-17
      • 2020-02-08
      • 2020-06-02
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      相关资源
      最近更新 更多