【发布时间】: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