我需要使用Guzzle檢查數據庫中的很多項目.例如,項目數量為2000-5000.將其全部加載到單個數組中太多了,因此我想將其分成多個塊:SELECT * FROM items LIMIT100.當最后一個項目發送到Guzzle時,則請求下一個100個項目.在“已滿”處理程序中,我應該知道哪個項目得到了響應.我看到這里有$index,它指向當前項目的數量.但是我無法訪問$items變量可見的范圍.無論如何,如果我什至可以通過use($items)訪問它,那么在循環的第二遍中,我會得到錯誤的索引,因為$items數組中的索引將從0開始,而$index則大于100.因此,此方法將不起作用.
$client = new Client();
$iterator = function() {
while($items = getSomeItemsFromDb(100)) {
foreach($items as $item) {
echo "Start item #{$item['id']}";
yield new Request('GET', $item['url']);
}
}
};
$pool = new Pool($client, $iterator(), [
'concurrency' => 20,
'fulfilled' => function (ResponseInterface $response, $index) {
// how to get $item['id'] here?
},
'rejected' => function (RequestException $reason, $index) {
call_user_func($this->error_handler, $reason, $index);
}
]);
$promise = $pool->promise();
$promise->wait();
我想我能做些什么
$request = new Request('GET', $item['url']);
$request->item = $item;
然后在“已實現”的處理程序中只是為了從$response獲取$request-這將是理想的.但正如我所看到的那樣,沒有辦法做類似$response-> getRequest()的事情.
關于如何解決這個問題的任何建議?
解決方法:
不幸的是,在Guzzle中不可能收到請求.有關更多詳細信息,請參見響應創建.
但是,您可以返回一個不同的Promise,并使用each_limit()代替Pool(內部,pool類只是對EachPromise的包裝).這是更通用的解決方案,可與任何類型的諾言一起使用.
$client = new Client();
$iterator = function () use ($client) {
while ($items = getSomeItemsFromDb(100)) {
foreach ($items as $item) {
echo "Start item #{$item['id']}";
yield $client
->sendAsync(new Request('GET', $item['url']))
->then(function (ResponseInterface $response) use ($item) {
return [$item['id'], $response];
});
}
}
};
$promise = \GuzzleHttp\Promise\each_limit(
$iterator(),
20,
function ($result, $index) {
list($itemId, $response) = $result;
// ...
},
function (RequestException $reason, $index) {
call_user_func($this->error_handler, $reason, $index);
}
);
$promise->wait();
標簽:guzzle,php
來源: https://codeday.me/bug/20191111/2021098.html