symfony 如何用Guzzle PHP在HTTP请求包之间放置延迟?

vptzau2j  于 2022-11-16  发布在  PHP
关注(0)|答案(1)|浏览(228)

我用Symfony构建了一个API,来自前端的数据是网站链接,我使用它们来同时创建和发送异步HTTPGET请求(使用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();
nbnkbykc

nbnkbykc1#

解决方案:

$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\组件\HttpClient\CurlHttpClient/的一个示例

相关问题