如何在 PHP 中从 Guzzle 异步 http 客户端获得最快的响应

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
}