gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 21:49:57 37 4
gpt4 key购买 nike

我在以下情况下需要帮助:我必须将 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?

最佳答案

我使用这段代码,它似乎有效:

    $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(), [

关于php - 如何使用 Guzzle 执行并发 POST 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46215636/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com