【问题标题】:How to get the fastest response from Guzzle async http client in PHP如何在 PHP 中从 Guzzle 异步 http 客户端获得最快的响应
【发布时间】:2021-04-22 15:44:40
【问题描述】:

我想使用 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 获得响应。

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

【问题讨论】:

标签: php asynchronous guzzle


【解决方案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
}

【讨论】:

    猜你喜欢
    • 2018-05-29
    • 1970-01-01
    • 2016-10-27
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2013-09-29
    • 2020-09-24
    相关资源
    最近更新 更多