如何使用Guzzle PHP在HTTP请求包之间设置延迟



我使用Symfony构建了一个API。在操作过程中,来自前端的数据是网站链接,我使用它们同时创建和发送异步HTTP GET请求(使用抓取这些网站的Scrapestack API(。但事实是,网站链接的数量可能很大,而且可以在同一个域上。为了不被域阻止,我想在同时发送的10个请求包之间设置1秒的延迟。使用PHP HTTP客户端Guzzle可以做到这一点吗(https://github.com/guzzle/guzzle)?我必须使用Pool吗?这是实际代码:

$promises = [];
$results = [];
foreach ($data as $d){
if(gettype($d) === 'string'){
$d = json_decode($d, true);
}
$url = sprintf('%s?%s', 'http://api.scrapestack.com/scrape', $this->createScrapestackRequestData($d['link']));
array_push($promises, $this->client->getAsync($url));
}
$responses = Utils::settle($promises)->wait();

解决方案:

$requests = [];
$results = [];
foreach ($data as $d){
if(gettype($d) === 'string'){
$d = json_decode($d, true);
}
array_push($requests, $this->curlClient->request('GET', $this->getUrlScrapestackApi($d['link'])));
}
foreach ($requests as $index => $response) {
if ($index !== 0 && $index % 10 === 0) {
sleep(1);
}
array_push($responses, $response->getContent());
}

信息:$this->curlClient是Symfony\Component\HttpClient\CurlHttpClient/的实例

最新更新