如何使用Guzzle执行并发POST请求?

时间:2017-09-14 09:39:38

标签: php post request guzzle pool

在以下情况下我需要帮助: 我必须将POST请求发送到API端点,该端点可以同时处理请求。但每个人都需要时间。为了减少时间,我想一次发送多个POST请求。

以下是一些代码片段:

use GuzzleHttp\Pool as GuzzlePool;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Psr7\Request as GuzzleRequest;

[...]

foreach ($aRequestParams as $sRequestParam) {
    $aRequestList[] = new GuzzleRequest('POST', $sRoute,
    [
//    'form_params' => [
//         'jsonString' => $sRequestParam
//      ]
        'body' =>  $sRequestParam
//      'multipart' => [
//           [
//               'name' => 'jsonString',
//               'contents' => $sRequestParam
//           ]
//       ]
     ]
     );
}
$oGuzzlePool = new GuzzlePool(new GuzzleClient(), $aRequestList, [
    'concurrency' => 8,
    'fulfilled' => [$this, 'processFulfilledCallback'],
    'rejected' => [$this, 'processRejectedCallback']
]);

$oPromise = $oGuzzlePool->promise();
$oPromise->wait();

回调函数在请求后调用,但缺少POST有效负载。我如何配置GuzzleRequest?

1 个答案:

答案 0 :(得分:0)

我使用此代码似乎有效:

    $oGuzzleClient = new GuzzleClient();
    $aRequestList = function() use ($oGuzzleClient, $aRequestParams, $sRoute) {
                    foreach ($aRequestParams as $sRequestParam) {
                        yield function() use ($oGuzzleClient, $sRequestParam, $sRoute) {
                            return $oGuzzleClient->postAsync($sRoute, [
                                'form_params' => [
                                    'jsonString' => $sRequestParam
                                ]
                            ]);
                        };
                    }
                };
$oGuzzlePool = new GuzzlePool($oGuzzleClient, $aRequestList(), [