Php Guzzle异步方法未异步触发HTTP请求
我有一个慢速函数,运行大约需要20秒,HTTP请求运行需要3.4秒 我想:Php Guzzle异步方法未异步触发HTTP请求,php,guzzle,guzzle6,Php,Guzzle,Guzzle6,我有一个慢速函数,运行大约需要20秒,HTTP请求运行需要3.4秒 我想: 触发一个异步HTTP请求(应该接近0,因为我没有等待响应) 然后运行一个缓慢的函数(~20秒) 然后在最后获得HTTP请求的结果。(应该差不多是0,因为我现在应该已经收到了响应,因为HTTP请求是异步完成的) 如果HTTP请求是异步完成的,那么步骤1和3应该在几乎没有时间的情况下完成 我使用了以下代码: $client = new Client(); $promise = $client->getAsync('h
$client = new Client();
$promise = $client->getAsync('http://www.fakeresponse.com/api/?sleep=3')->then(
function (ResponseInterface $res) {
return \GuzzleHttp\json_decode($res->getBody()->getContents(), true);
},
function (RequestException $e) {
throw $e;
}
);
// Slow function
$start = microtime(true);
$this->slowFunction(); // ~20s
dump($end);
$start = microtime(true);
$promise->wait();
$end = microtime(true) - $start;
dump($end); // Should be 0 if running async
输出:
19.018649101257
3.3757498264313
这意味着步骤3运行了~3.4s,这意味着->getAsync
没有触发HTTP请求。而是在->等待时启动它
如何使HTTP请求异步激发?您可以使用lib与php异步激发某些内容,例如:
<?php
class MyThread extends Thread{
public $promise;
public $terminated;
public function __construct($promise) {
$this->terminated=false;
$this->promise=$promise;
}
public function run(){
$this->promise->wait();
$this->terminated=true;
}
}
$client = new Client();
$promise = $client->getAsync('https://www.foaas.com/version')->then(
function (ResponseInterface $res) {
return \GuzzleHttp\json_decode($res->getBody()->getContents(), true);
},
function (RequestException $e) {
throw $e;
}
);
$start = microtime(true);
print $start;
$thread = new MyThread($promise);
while(!$thread->terminated){
usleep(1);
}
$end = microtime(true) - $start;
print " - ".$end;