GuzzleHttps - 如何发送异步。通过 POST 的数据(使用池)

GuzzleHttps - How to send async. data via POST (using Pool)

我正在尝试通过 Guzzle 库中的 POOL 发送 POST 数据。但是,在发送数据的地址 POST 完全是空的 - 我不明白。

$client = new Client();

$requests = function ()
{
    foreach($this->urls as $url)
    {
        yield new Request('POST', $url, [
            'body' => '...'
        ]);
    }
 };

我也尝试了 form_params 和 multiparts,但再次不起作用(POST 又是空的 $_REQUEST 和 $_GET)。

当然还有这段代码(为了完整性):

$pool = new Pool($client, $requests(), [
    'concurrency' => count($this->urls),
    'fulfilled'   => function ($response) {},
    'rejected' => function ($reason) {},
});

$promise = $pool->promise();
$promise->wait();

Guzzle正确发送请求(在第二台服务器上输入),但本身没有任何数据。

我做错了什么?谢谢!

编辑:

我只是想用 Guzzle 替换这段代码(现在循环重复):

$ch = curl_init();
$url = 'https://example.cop';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'mehehe_net');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 59000);
curl_setopt($ch, CURLOPT_POST, true);
$dt = ["data" => json_encode($queue)];

curl_setopt($ch, CURLOPT_POSTFIELDS, $dt);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$cont = curl_exec($ch);
curl_close($ch);

这个解决方案效果很好! :-)

$pss = [];
$client = new Client();
$uri = "https://example.com";
foreach($data as $alarm)
{
    $pss[] = $client->postAsync($uri, ['form_params' => ["alarms" => json_encode($alarm)]])->then(function ($response) use ($alarm)
    {
         // $response->getBody();
    });
 }
 \GuzzleHttp\Promise\unwrap($permis);

不要忘记在循环后使用 unwrap(等待)! :-)

解决方案的其他信息:考虑将 each_limit() 与生成器一起使用,而不是 unwrap

它将允许您控制并发级别(并行查询的数量)。当您有大量请求并且在服务器端有一些限制时(通常对来自客户端的同时请求数有一些限制),它很有用。

$generator = function () {
    return $client->postAsync($uri, ['form_params' => ["alarms" => json_encode($alarm)]])->then(function ($response) {
        // ...
    });
}

// Allow only 10 simultaneous requests.
each_limit($generator(), 10)->wait();

阅读 this article 了解更多详情。

这是我使用的解决方案。

$requests = function ($endpoints, $data) {

            foreach ($endpoints as $endpoint) {
                yield new Psr7\Request(
                   'POST', 
                   $endpoint, 
                   ['Content-Type' => 'application/x-www-form-urlencoded'],
                   http_build_query($data, null, '&'));
            }
            echo "\n";
        };