【问题标题】:Use Guzzle pool instead of guzzle promises使用 Guzzle 池而不是 Guzzle Promise
【发布时间】:2023-03-27 14:25:01
【问题描述】:

我正在使用 guzzle 承诺发送并发请求,但我想控制并发性,这就是我想使用 guzzle 池的原因。我如何将 guzzle promise 转换为 guzzle pool。这是我的代码:

 public function getDispenceryforAllPage($dispencery)
    {
        $GetAllproducts = [];
        $promiseGetPagination = $this->client->getAsync($dispencery)
            ->then(function ($response) {
                return $this->getPaginationNumber($response->getBody()->getContents());           
                });

               $Pagination = $promiseGetPagination->wait();

                $pagearray = array();

                    for($i=1;$i<=$Pagination; $i++){
                        $pagearray[] = $i;

                        }


                foreach($pagearray as $page_no) {

                        $GetAllproducts[] = $this->client->getAsync($dispencery.'?page='.$page_no)
                        ->then(function ($response) {

                            $promise =  $this->getData($response->getBody()->getContents()); 
                            return $promise;       
                            });


        }
       $results =  GuzzleHttp\Promise\settle($GetAllproducts)->wait();
        return $results; 
    }

【问题讨论】:

    标签: php httprequest guzzle guzzle6


    【解决方案1】:

    我有以下 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();
    }
    

    【讨论】:

      【解决方案2】:

      只需将each_limit()each_limit_all()(而不是settle())与生成器一起使用。

      function getDispenceryforAllPage($dispencery)
      {
          $promiseGetPagination = $this->client->getAsync($dispencery)
              ->then(function ($response) {
                  return $this->getPaginationNumber($response->getBody()->getContents());
              });
      
          $Pagination = $promiseGetPagination->wait();
      
          $pagearray = range(1, $Pagination);
      
          $requestGenerator = function () use ($dispencery, $pagearray) {
              foreach ($pagearray as $page_no) {
                  yield $this->client->getAsync($dispencery . '?page=' . $page_no)
                      ->then(function ($response) {
                          return $this->getData($response->getBody()->getContents());
                      });
              }
          };
      
          // Max 5 concurrent requests
          $results = GuzzleHttp\Promise\each_limit_all($requestGenerator(), 5)->wait();
      
          return $results;
      }
      

      【讨论】:

      • each_limit_all() 在我的测试中按预期工作,是的。如果您一次看到所有请求,请检查您是否真的使用了生成器(而不是一个简单的数组,例如一次创建所有请求)。 @winmutt,反正不看代码很难说什么。
      【解决方案3】:

      我已修改您的代码以支持池。

      class GuzzleTest
      {
          private $client;
      
          public function __construct($baseUrl)
          {
              $this->client = new \GuzzleHttp\Client([// Base URI is used with relative requests
                  'base_uri' => $baseUrl,
                  // You can set any number of default request options.
                  'timeout'  => 2.0,]);
      
          }
      
      
          public function getDispenceryforAllPage($dispencery)
          {
              $GetAllproducts = [];
              $promiseGetPagination = $this->client->getAsync($dispencery)
                  ->then(function ($response) {
                      return $this->getPaginationNumber($response->getBody()->getContents());
                  });
      
              $Pagination = $promiseGetPagination->wait();
      
              $pagearray = array();
      
              for ($i = 1; $i <= $Pagination; $i++) {
                  $pagearray[] = $i;
      
              }
      
      
              $pool = new \GuzzleHttp\Pool($this->client, $this->_yieldRequest($pagearray, $dispencery), [
                  'concurrency' => 5,
                  'fulfilled' => function ($response, $index) {
                      // this is delivered each successful response
      
                  },
                  'rejected' => function ($reason, $index) {
                      // this is delivered each failed request
                  },
              ]);
      
              // Initiate the transfers and create a promise
              $poolPromise = $pool->promise();
      
              // Force the pool of requests to complete.
              $results = $poolPromise->wait();
      
      
      
              return $results;
          }
      
          private function _yieldRequest($pagearray, $dispencery){
      
              foreach ($pagearray as $page_no) {
      
                  $uri = $dispencery . '?page=' . $page_no;
      
                  yield function() use ($uri) {
                      return $this->client->getAsync($uri);
                  };
      
      
              }
      
      
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2016-08-01
        • 2019-09-16
        • 1970-01-01
        • 2017-07-09
        • 1970-01-01
        • 2020-10-11
        • 2021-03-10
        • 2019-03-07
        • 2017-11-19
        相关资源
        最近更新 更多