2015-10-15 136 views
0

我想通过使用Guzzle的并发请求功能来加速脚本,但是我似乎需要花费相同的时间。为什么Guzzle的并发请求功能更快?

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

在原始脚本中,没有使用并发请求,它会拉出100个帖子,然后通过请求插入的数据进行循环。

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个职位,然后使用狂饮的并发请求的功能加载了透过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

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

说了这么多,你可能会看到更好的结果GuzzleHttp\Pool。我已经有了很好的结果。你的具体情况可能有所不同