发送异步请求,而无需等待使用 guzzle 的响应

2022-08-30 20:08:40

我有以下两个功能

public function myEndpoint(){
    $this->logger->debug('Started');
    $this->guzzle->requestAsync('post', 'http://myurl.com/doNotWait')->wait();
    $this->logger->debug("I shouldn't wait");
}

public function doNotWait(){
    sleep(10);
    $this->logger->debug("You shouldn't wait");
}

现在我需要在日志中看到的是:

Started
I shouldn't wait
You shouldn't wait

但我所看到的

Started
You shouldn't wait
I shouldn't wait

我也尝试使用以下方法:

方式 #1

public function myEndpoint(){
    $this->logger->debug('Started');
    $this->guzzle->requestAsync('post', 'http://myurl.com/doNotWait', ['synchronous' => false])->wait();
    $this->logger->debug("I shouldn't wait");
}

方式 #2

public function myEndpoint(){
    $this->logger->debug('Started');
    $this->guzzle->requestAsync('post', 'http://myurl.com/doNotWait');

    $queue = \GuzzleHttp\Promise\queue()->run();
    $this->logger->debug("I shouldn't wait");
}

但结果从来都不是想要的。有什么想法吗?我正在使用Guzzle 6.x。


答案 1

要将其从未回答列表中删除,


Guzzle不支持在没有深度黑客攻击的情况下“开火即忘记”的异步请求。

异步方法是 的抽象,它返回一个承诺。请参阅 https://github.com/guzzle/promises#synchronous-wait - 调用“用于同步强制完成承诺”。Client::requestAsync()Promise::wait()

参考资料: https://github.com/guzzle/guzzle/issues/1429#issuecomment-197119452


答案 2

如果您不关心响应,则应执行以下操作:

try {
    $this->guzzle->post('http://myurl.com/doNotWait', ['timeout' => 1]);
} catch (\GuzzleHttp\Exception\ConnectException $e) {
    // do nothing, the timeout exception is intended
}

因此,此处的请求将花费 1 秒,代码执行将继续。


推荐