为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕码人2483693 2021-10-08 15:38:06
我想使用 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 得到响应(承诺被拒绝,没有这样的主机等)。如何立即获得最快的响应并忽略其余部分?
查看完整描述

1 回答

?
侃侃尔雅

TA贡献1801条经验 获得超16个赞

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


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

}


查看完整回答
反对 回复 2021-10-08
  • 1 回答
  • 0 关注
  • 233 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信