如何获取并发Guzzle Promise池的已用时间

时间:2017-01-19 22:23:20

标签: guzzle guzzle6 guzzlehttp

我使用Guzzle php版本:6.2.2。是否可以在下面的代码中发送Promise运行的已用时间?例如。每隔5秒,将经过的时间发送到某个功能?

    $client = new Client([
        'base_uri' => BASE_URL . 'sync/import', // Base URI is used with relative requests
        'timeout'  => 0, // 0 no timeout for operations and watching Promises
        'verify' => true
    ]);

    $requests = function ($syncRequests) {
        foreach ($syncRequests as $key => $headers) {
            yield new Request('PUT', '', ['Content-type' => 'application/json'], json_encode(['json' => ['sync' => $headers]]));
        }
    };

    $pool = new Pool($client, $requests($this->syncRequests), [
        'concurrency' => 10,
        'fulfilled' => function ($response, $index) {
            $this->promiseFulfilled($response, $index);
        },
        'rejected' => function ($reason, $index) {
            $this->promiseRejected($reason, $index);
        },
    ]);

    $promise = $pool->promise(); // Initiate the transfers and create a promise
    $promise->wait(); // Force the pool of requests to complete.

例如:

    $pool = new Pool($client, $requests($this->syncRequests), [
        'concurrency' => 10,
        'while' => function () { // CALLED WHILE THE CONCURRENT REQUESTS ARE RUNNING!!
            $this->elapsedTime();
        },
        'fulfilled' => function ($response, $index) {
            $this->promiseFulfilled($response, $index);
        },
        'rejected' => function ($reason, $index) {
            $this->promiseRejected($reason, $index);
        },
    ]);

3 个答案:

答案 0 :(得分:2)

您可以使用"progress" request option制作适合的内容。对于池中的每个请求,这将为CURLOPT_PROGRESSFUNCTION连接回调。您可以获得触发这些回调的时间,并将其与执行池之前的时间进行比较。

另一种选择可能是将自定义TaskQueue注入promise library's queue() function并挂钩自定义逻辑。

答案 1 :(得分:0)

您可以在已完成的功能中调用一个函数。每次请求完成时都会调用履行的函数

在履行的功能中,您可以调用另一个功能,例如更新数据库中请求的进度。该函数可以是当前对象的成员。因此,在您完成的功能中,您可以拥有以下行:

$this->UpdateProgress();

答案 2 :(得分:0)

这可能无法回答您的问题,但是对于正在搜索如何获取每个Promise的经过时间的任何人,您都可以这样做:

$startTime = microtime(true);
$pool = new Pool($client, $requests(100), [
    'concurrency' => 5,
    'fulfilled' => function (Response $response, $index) {
        $endTime = microtime(true);
        $executionTime = round($endTime - $this->startTime, 2);
        // dd($executionTim); or log it
    },
    'rejected' => function (RequestException $reason, $index) {
        // this is delivered each failed request
    },
]);

类似地,您可以使用then来完成

$promise = $client->requestAsync('GET', 'http://httpbin.org/get');
$startTime = microtime(true);
$promise->then(
    function (ResponseInterface $res) {
        $endTime = microtime(true);
        $executionTime = round($endTime - $this->startTime, 2);
        // dd($executionTim); or log it
    },
    function (RequestException $e) {
        echo $e->getMessage() . "\n";
        echo $e->getRequest()->getMethod();
    }
);