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

我想使用 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 得到响应(承诺被拒绝,没有这样的主机等)。


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


慕码人2483693
浏览 237回答 1
1回答

侃侃尔雅

解决方案是在收到第一个响应时取消剩余的请求。// 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}
打开App,查看更多内容
随时随地看视频慕课网APP