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 (wait) !: -)

这是我使用的解决方案。

$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";
        };

解决方案的附加信息:考虑将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();