我想通过使用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;
}
我认为这将大大减少时间,但它需要与原始脚本相同的时间。为什么会这样?我错过了什么?感谢您的任何帮助。