Guzzle 5.3 - Get request duration for asynchronous

2019-08-06 05:22发布

问题:

I am timing synchronous requests as suggested here: guzzle-6-get-request-total-time

But I also have a guzzle pool with two or more requests that get batch-executed asynchronously. I need to retrieve the duration each request took to return.

I am certain there is a simple way to retrieve this information that I am just overlooking. The infos are in the underlying curl, I am just unsure how to get to them.

回答1:

Turns out, by listening to the complete event, one can catch the entire transferinfo:

    $client = new \GuzzleHttp\Client();
    $guzzleRequests = $this->getGuzzleRequests();

    foreach($guzzleRequests as $myRequest)
    {
        $myRequest->getEmitter()->on(
            'complete',
            function (CompleteEvent $e) {
                var_dump($e->getTransferInfo());
                var_dump($e->getTransferInfo()['url']);
                var_dump($e->getTransferInfo()['total_time']);
            }
        );
    }

    // Results is a GuzzleHttp\BatchResults object.
    $results = Pool::batch($client, $guzzleRequests);

The TransferInfo has much more, but all I needed was the request url to identify which API was being requested and the total time as the duration.