Guzzle Pool:等待请求

时间:2017-03-12 23:21:56

标签: php curl guzzle guzzlehttp

是否可以让Guzzle池等待请求?

现在我可以动态地向池添加请求,但是一旦池为空,guzzle就会停止(显然)。

当我同时处理10个左右的页面时,这是一个问题,因为我的请求数组将为空,直到处理结果HTML页面并添加新链接。

这是我的发电机:

$generator = function () {
  while ($request = array_shift($this->requests)) {
    if (isset($request['page'])) {
      $key = 'page_' . $request['page'];
    } else {
      $key = 'listing_' . $request['listing'];
    }

    yield $key => new Request('GET', $request['url']);                                          
  }
  echo "Exiting...\n";
  flush();
};

我的游泳池:

$pool = new Pool($this->client, $generator(), [
  'concurrency' => function() {
    return max(1, min(count($this->requests), 2));
  },
  'fulfilled' => function ($response, $index) {
      // new requests may be added to the $this->requests array here
  }
  //...
]);

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

@Alexey Shockov回答后编辑的代码:

$generator = function() use ($headers) {
  while ($request = array_shift($this->requests)) {
    echo 'Requesting ' . $request['id'] . ': ' . $request['url'] . "\r\n";

    $r = new Request('GET', $request['url'], $headers);

    yield 'id_' . $request['id'] => $this->client->sendAsync($r)->then(function($response, $index) {
      echo 'In promise fulfillment ' . $index . "\r\n";
    }, function($reason, $index) {
      echo 'in rejected: ' . $index . "\r\n";
    });
  }
};

$promise = \GuzzleHttp\Promise\each_limit($generator(), 10, function() {
  echo 'fullfilled' . "\r\n";
  flush();
}, function($err) {
  echo 'rejected' . "\r\n";
  echo $err->getMessage();
  flush();
});
$promise->wait();

5 个答案:

答案 0 :(得分:3)

不幸的是,你不能用生成器来做,只能使用自定义迭代器。

我准备了 a gist with the full example ,但主要的想法是创建一个迭代器,它将以两种方式改变其状态(它可以在结束后再次生效)。

psysh中的ArrayIterator示例:

>>> $a = new ArrayIterator([1, 2])
=> ArrayIterator {#186
     +0: 1,
     +1: 2,
   }
>>> $a->current()
=> 1
>>> $a->next()
=> null
>>> $a->current()
=> 2
>>> $a->next()
=> null
>>> $a->valid()
=> false
>>> $a[] = 2
=> 2
>>> $a->valid()
=> true
>>> $a->current()
=> 2

考虑到这个想法,我们可以将这样的动态迭代器传递给Guzzle并让它完成工作:

// MapIterator mainly needed for readability.
$generator = new MapIterator(
    // Initial data. This object will be always passed as the second parameter to the callback below
    new \ArrayIterator(['http://google.com']),
    function ($request, $array) use ($httpClient, $next) {
        return $httpClient->requestAsync('GET', $request)
            ->then(function (Response $response) use ($request, $array, $next) {
                // The status code for example.
                echo $request . ': ' . $response->getStatusCode() . PHP_EOL;
                // New requests.
                $array->append($next->shift());
                $array->append($next->shift());
            });
    }
);
// The "magic".
$generator = new ExpectingIterator($generator);
// And the concurrent runner.
$promise = \GuzzleHttp\Promise\each_limit($generator, 5);
$promise->wait();

正如我之前所说,完整示例位于the gist MapIteratorExpectingIterator

答案 1 :(得分:1)

从问题看来,您可以将聚合回调直接移动到查询中。在这种情况下,池将始终等待您的处理代码,因此您可以随时添加新请求。

生成器可以返回请求或承诺,并且承诺可以以不同的方式组合在一起。

$generator = function () {
    while ($request = array_shift($this->requests)) {
        if (isset($request['page'])) {
            $key = 'page_' . $request['page'];
        } else {
            $key = 'listing_' . $request['listing'];
        }

        yield $this->client->sendAsync('GET', $request['url'])
            ->then(function (Response $response) use ($key) {
            /*
             * The fullfillment callback is now connected to the query, so the 
             * pool will wait for it.
             * 
             * $key is also available, because it's just a closure, so 
             * no $index needed as an argument.
             */
        });
    }
    echo "Exiting...\n";
    flush();
};

$promise = \GuzzleHttp\Promise\each_limit($generator(), [
    'concurrency' => function () {
        return max(1, min(count($this->requests), 2));
    },
    //...
]);

$promise->wait();

答案 2 :(得分:1)

  

正如我之前所说,完整的例子是在gist中,使用MapIterator和ExpectingIterator

迭代器在php<上再次生效7,使用arrayIterator的示例和使用MapIterator的示例都在初始池耗尽后停止...

另一方面它可以在早期版本的php上运行,前提是你使用 - >在迭代器而不是[] push上附加方法。

答案 3 :(得分:0)

答案是肯定的。你只需要更多的发电机。并将您的请求解析和排队逻辑分离为异步设计。而不是使用数组来处理池将要发出的请求并等待它需要本身是一个生成器,它从初始列表中产生新请求,并从解析后的响应中添加请求,直到发送所有请求并解析结果请求为止。解析(重复)或遇到停止条件。

答案 4 :(得分:0)

如果您可以使用postAsync / getAsync左右,则可以使用以下框架,

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();
}