是否可以使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();
最佳答案
不幸的是,您不能使用生成器来做到这一点,只能使用自定义迭代器。
我准备了 a gist with the full example ,但是主要思想是创建一个Iterator,它将以两种方式更改其状态(结束后可以再次变得有效)。
psysh中的ArrayIterator的示例:
>>> $a = new ArrayIterator([1, 2])
=> ArrayIterator {#186
+0: 1,
+1: 2,
}
>>> $a->current()
=> 1
>>> $a->next()
=> null
>>> $a->current()
=> 2
>>> $a->next()
=> null
>>> $a->valid()
=> false
>>> $a[] = 2
=> 2
>>> $a->valid()
=> true
>>> $a->current()
=> 2
考虑到这个想法,我们可以将这样的动态迭代器传递给Guzzle并让其完成工作:
// MapIterator mainly needed for readability.
$generator = new MapIterator(
// Initial data. This object will be always passed as the second parameter to the callback below
new \ArrayIterator(['http://google.com']),
function ($request, $array) use ($httpClient, $next) {
return $httpClient->requestAsync('GET', $request)
->then(function (Response $response) use ($request, $array, $next) {
// The status code for example.
echo $request . ': ' . $response->getStatusCode() . PHP_EOL;
// New requests.
$array->append($next->shift());
$array->append($next->shift());
});
}
);
// The "magic".
$generator = new ExpectingIterator($generator);
// And the concurrent runner.
$promise = \GuzzleHttp\Promise\each_limit($generator, 5);
$promise->wait();
如我之前所说,的完整示例在the gist 中,其中包括
MapIterator
和ExpectingIterator
。关于php - 食欲池: Wait for Requests,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42754389/