避免在Guzzle 6 Asynchronous by Pool

时间:2016-05-17 19:32:38

标签: php guzzle guzzle6

使用Guzzle 6,我使用以下代码测试了Pool / Promise异步:

    $client = new  \GuzzleHttp\Client();
    $urls = [];
    for($i = 1; $i<10; $i++) {
       $urls[] = ''https://httpbin.org/get?id='.$i;
    }    

    $requests = function ($urls){
        if(!empty($urls)) {
            foreach($urls as $uri){
                yield new \GuzzleHttp\Psr7\Request('GET', $uri);
            }
        }
    };
    $values = [];
    $pool = new \GuzzleHttp\Pool($client, $requests($urls), [
        'concurrency' => 5,
        'fulfilled' => function ($response, $index) use (&$values){
            // this is delivered each successful response
            return $values[]=$response->getStatusCode();
        },
        'rejected' => function ($reason, $index){
            // this is delivered each failed request
            //dd($reason);
            return $reason->getResponse();
        },
    ]);

// Initiate the transfers and create a promise
    $promise = $pool->promise();

// Force the pool of requests to complete.
    $promise->wait();
    var_dump($values);

是否有一种方法或重构方式可以让我不通过引用$ value而是通过$promise->wait();来接收结果?

见:http://guzzle.readthedocs.io/en/latest/quickstart.html#async-requests

如果我们想忽略所有被拒绝的promises,那么有一种方法可以做Promise \ Settle,而wait将返回结果数组中返回的值。

1 个答案:

答案 0 :(得分:1)

我不确定你要做什么。您需要传递$values来存储已完成的请求,但不需要通过引用传递它。但是,要将所有回复放在一个位置,您可以使用batch()类的静态Pool方法:

$responses = Pool::batch($client, $requests(10), [
    'concurrency' => 5,
    'fulfilled' => function ($response, $index) {
    },
    'rejected' => function ($reason, $index) {
    },
]);

然后,通过迭代Response

,您有一个$responses类的对象
foreach ($responses as $response) {
    var_dump($response->getBody()->getContents());
}