一般我们的请求都是阻塞的,如果需要同时进行多请求的话,就得需要使用并发请求了。
Guzzle你可以使用Promise和异步请求来同时发送多个请求:
$client = new Client();
// 创建一个请求列表
$promises = [
'baidu' => $client->getAsync('https://www.baidu.com/'),
'jd' => $client->getAsync('http://www.jd.com/'),
'earnp' => $client->getAsync('http://bbs.earnp.com/'),
];
// 等待所有请求完成
$results = Promise\unwrap($promises);
// 查看请求结果
$baidu = $results['baidu']->getHeader('Content-Length');
$jd = $results['jd']->getHeader('Content-Length');
$earnp = $results['earnp']->getHeader('Content-Length');
dd($jd);
上面确定了并发的数量,当你想发送不确定数量的请求时,可以使用GuzzleHttp\Pool对象:
$client = new Client();
$requests = function ($total) {
$uri = 'http://baidu.com';
for ($i &#61; 0; $i <$total; $i&#43;&#43;) {
yield new Request(&#39;GET&#39;, $uri);
}
};
$pool &#61; new Pool($client, $requests(100), [
&#39;concurrency&#39; &#61;> 5,
&#39;fulfilled&#39; &#61;> function ($response, $index) {
// 成功的响应。
},
&#39;rejected&#39; &#61;> function ($reason, $index) {
// 失败的响应
},
]);
// 构建请求
$promise &#61; $pool->promise();
// 等待请求池完成。
$promise->wait();
这样我们就可以发布并发请求了
原创文章&#xff0c;转载请注明 &#xff1a;[ laravel爬虫实战--基础篇 ] guzzle发送并发请求 - Laravel学习网
原文出处&#xff1a; https://phpartisan.cn/news/44.html
问题交流群 &#xff1a;168117787