Guzzle并发去请求图片并保存到本地
现在有个小需求,需要用Guzzle并发去请求图片并保存到本地,并发的数量是不固定的,下面测试代码,请教大家指点一下!
public function onGoodsSynchronizationEvent(GoodsSynchronizationEvent $goodsSynchronizationEvent,Client $client){
$requests = function (array $imageInfo) {
foreach ($imageInfo as $image){
yield new Request('GET', $image['url']);
}
};
$pool = new Pool($client, $requests($goodsSynchronizationEvent->imageInfo), [
'concurrency' => 5,
'fulfilled' => function ($response, $index) {
// this is delivered each successful response
},
'rejected' => function ($reason, $index) {
// this is delivered each failed request
},
]);
// Initiate the transfers and create a promise
$promise = $pool->promise();
// Force the pool of requests to complete.
$promise->wait();
}
我只了解请求单个可以这样使用
$client->get($rul,['save_to'=>$fileName);
关于 LearnKu
这是看了文档后修改后的代码,折腾了半天
你这
$imageInfo都已经是一个完整地址的数组了,你直接用文档里面前一个例子不就好了么…… 🤨,还跑去搞相对复杂的 Pool。文档中的 当希望发送的请求数量不确定时,可以使用 GuzzleHttp Pool 对象。 可不是指你这样的场景,这里应该是指像 Redis 的 scan 和 ES 的 scroll API 这种情况,或者从远程(迭代器)不断有获取的情况下。
而你这里图片地址都已经是一个确定的数组了,就直接用文档种前面的里面就好了。
github.com/mouyong/php-support/rel... 试试?
@Rache1 你说的列子是不是这个并发请求?