是否可能让Guzzle池等待请求?
目前,我可以动态地向池中添加请求,但是一旦池为空,guzzle就会停止(显然)。
当我同时处理大约10个页面时,这是一个问题,因为我的请求数组将在处理完生成的HTML页面并添加新链接之前为空。
这是我的生成器:
$generator = function () {
while ($request = array_shift($this->requests)) {
if (isset($request['page'])) {
$key = 'page_' . $request['page'];
} else {
$key = 'listing_' . $request['listing'];
}
yield $key => new Request('GET', $request['url']);
}
echo "Exiting...\n";
flush();
};
还有我的游泳池:
$pool = new Pool($this->client, $generator(), [
'concurrency' => function() {
return max(1, min(count($this->requests), 2));
},
'fulfilled' => function ($response, $index) {
// new requests may be added to the $this->requests array here
}
//...
]);
$promise = $pool->promise();
$promise->wait();
@Alexey Shockov回答后编辑的代码:
$generator = function() use ($headers) {
while ($request = array_shift($this->requests)) {
echo 'Requesting ' . $request['id'] . ': ' . $request['url'] . "\r\n";
$r = new Request('GET', $request['url'], $headers);
yield 'id_' . $request['id'] => $this->client->sendAsync($r)->then(function($response, $index) {
echo 'In promise fulfillment ' . $index . "\r\n";
}, function($reason, $index) {
echo 'in rejected: ' . $index . "\r\n";
});
}
};
$promise = \GuzzleHttp\Promise\each_limit($generator(), 10, function() {
echo 'fullfilled' . "\r\n";
flush();
}, function($err) {
echo 'rejected' . "\r\n";
echo $err->getMessage();
flush();
});
$promise->wait();
Pool
类内部使用与each_limit()
相同的机制。我创建了一个单独的包(基于上面的代码)来尽可能简化事情,请看一下:https://github.com/alexeyshockov/guzzle-dynamic-pool/blob/master/example/app1.php - Alexey Shokov