[英]How to get the fastest response from Guzzle async http client in PHP
我想使用 Guzzle 將 HTTP 請求發送到多個端點,並且我想使用第一個到達的響應,而不是等待所有請求完成。
我的代碼:
$client = new \GuzzleHttp\Client();
$p1 = $client->requestAsync('GET', 'slow.host');
$p2 = $client->requestAsync('GET', 'fast.host');
$any = \GuzzleHttp\Promise\any([$p1, $p2]);
$response = $any->wait();
我原以為只要承諾 ($p1, $p2) 中的任何一個得到解決,我就會得到回復,但是這不是它與 Guzzle 的工作方式。 Guzzle 將始終等待$p1
解決或拒絕,即使它需要很長時間。
從上面的例子來看,如果 slow.host 需要 10 秒發送響應,而 fast.host 需要 1 秒發送響應,我將不得不等待 10 秒。 只有在 slow.host 完全失敗的情況下,我才會從 fast.host 得到響應(承諾被拒絕,沒有這樣的主機等)。
如何立即獲得最快的響應並忽略其余部分?
解決方案是在收到第一個響應時取消剩余的請求。
// Create your promises here.
// All the promises must use the same guzzle client!
$promises = create_requests();
$any = \GuzzleHttp\Promise\any($promises);
// when data is received from any of the requests:
$any->then(function() use ($promises) {
// cancel all other requests without waiting for them to fulfill or reject
foreach ($promises as $promise) {
$promise->cancel();
}
});
try {
// this actually fires all the requests
$data = $any->wait();
} catch (Exception $e) {
// Exception will be thrown if ALL requests fail
// Handle exception here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.