【问题标题】:Guzzle pool in PHP applicationPHP 应用程序中的 Guzzle 池
【发布时间】:2020-08-25 12:41:54
【问题描述】:

我正在尝试在 PHP 中使用 Guzzle 池。但是我在处理 ASYNC 请求时遇到了困难。下面是代码sn-p。

    $client = new \GuzzleHttp\Client();

    function test() 
    {
        $client = new \GuzzleHttp\Client();   
        $request = $client->createRequest('GET', 'http://l/?n=0', ['future' => true]);

        $client->send($request)->then(function ($response) {
            //echo 'Got a response! ' . $response;
            return "\n".$response->getBody();
        });

    }
    $res = test();
    var_dump($res); // echoes null - I know why it does so but how to resolve the issue.

有没有人可以让函数等待并得到正确的结果。

【问题讨论】:

    标签: php promise guzzle reactphp


    【解决方案1】:

    如果你可以返回它,它在代码风格上就不会是异步的。返回承诺并在外面打开它。

    function test() 
    {
       $client = new \GuzzleHttp\Client();   
       $request = $client->createRequest('GET', 'http://l/?n=0', ['future' => true]);
    
       // note the return
       return $client->send($request)->then(function ($response) {
           //echo 'Got a response! ' . $response;
           return "\n".$response->getBody();
       });   
    }
    test()->then(function($body){
         echo $body; // access body here inside `then`
    });
    

    【讨论】:

      【解决方案2】:

      我想分享另一个使用 guzzle 6、postAsync 和 Pool 的示例。

      function postInBulk($inputs)
      {
          $client = new Client([
              'base_uri' => 'https://a.b.com'
          ]);
          $headers = [
              'Authorization' => 'Bearer token_from_directus_user'
          ];
      
          $requests = function ($a) use ($client, $headers) {
              for ($i = 0; $i < count($a); $i++) {
                  yield function() use ($client, $headers) {
                      return $client->postAsync('https://a.com/project/items/collection', [
                          'headers' => $headers,
                          'json' => [
                              "snippet" => "snippet",
                              "rank" => "1",
                              "status" => "published"
                          ]        
                      ]);
                  };
              }
              
          };
      
          $pool = new Pool($client, $requests($inputs),[
              'concurrency' => 5,
              'fulfilled' => function (Response $response, $index) {
                  // this is delivered each successful response
              },
              'rejected' => function (RequestException $reason, $index) {
                  // this is delivered each failed request
              },
          ]);
      
          $pool->promise()->wait();
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-27
        • 2021-10-14
        • 1970-01-01
        • 2015-02-28
        • 1970-01-01
        • 1970-01-01
        • 2010-11-19
        • 2010-09-26
        • 2016-04-17
        相关资源
        最近更新 更多