2016-09-12 25 views
1

我试图通过POOL在发送库中发送POST数据。但是,在数据发送的地址POST是完全空的 - 我不明白。GuzzleHttps - 如何发送异步。数据通过POST(使用池)

$client = new Client(); 

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

我也试过form_params和multipart内容,不工作了(POST是空的也再次$ _REQUEST & $ _GET)。

当然这一段代码(出于完整性):

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

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

狂饮正确地发送请求(第二服务器上输入),但其本身不具有任何数据。

我在做什么错?谢谢!

编辑:

我只是想将这段代码有狂饮(重复的周期现在):

$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); 

回答

1

该解决方案的工作太棒了! :-)

$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); 

不要忘了在循环之后使用解包(等待)! :-)

0

解决方案的其他信息:考虑将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了解更多详情。

1

这是我使用的解决方案。

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