【问题标题】:Guzzle async method is not firing HTTP request asynchronouslyGuzzle 异步方法未异步触发 HTTP 请求
【发布时间】:2018-04-22 19:03:26
【问题描述】:

我有一个缓慢的函数,运行大约需要 20 秒,而 HTTP 请求需要 3.4 秒才能运行。

我想:

  1. 触发异步 HTTP 请求(应该几乎是 0,因为我不等待响应)
  2. 然后运行一个慢速函数(~20s)
  3. 然后在最后得到HTTP请求的结果。 (应该几乎是 0,因为我现在应该已经收到响应,因为 HTTP 请求是异步完成的)

如果 HTTP 请求是异步完成的,那么第 1 步和第 3 步应该几乎可以立即完成。

我使用了以下代码:

$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.4 秒,这意味着 ->getAsync 没有触发 HTTP 请求。相反,它会在 ->wait 上触发它。

如何让 HTTP 请求异步触发?

【问题讨论】:

    标签: php guzzle guzzle6


    【解决方案1】:

    您可以使用pthreads 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; 
    

    【讨论】:

      最近更新 更多