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

时间:2019-07-14 12:26:52

标签: php asynchronous guzzle

我想使用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的工作原理。食尸鬼将永远等待$p1解决或拒绝,即使这需要永远。

在上面的示例中,如果slow.host花10秒发送响应,而fast.host花1秒发送响应,则无论如何我都必须等待10秒。只有在slow.host完全失败(承诺被拒绝,没有此类主机等)的情况下,我才能从fast.host获得响应。

如何立即获得最快的响应,而忽略其余部分?

1 个答案:

答案 0 :(得分:0)

解决方案是在收到第一个响应时取消剩余的请求。

// 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
}