2016-09-12 28 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"; 
     };