如何同时执行多个Guzzle请求?

时间:2013-10-22 14:06:55

标签: php curl guzzle

我可以使用Guzzle执行单个请求,到目前为止我对Guzzle的性能非常满意,但我在Guzzle API中读到了一些关于MultiCurl和Batching的内容。

有人可以向我解释如何同时发出多个请求吗?尽可能异步。我不知道这是不是他们对MultiCurl的意思。同步也不是问题。我只是想同时或非常接近(短时间)做多个请求。

3 个答案:

答案 0 :(得分:22)

来自文档: http://guzzle3.readthedocs.org/http-client/client.html#sending-requests-in-parallel

对于一个易于使用的解决方案,它返回映射到响应或错误的请求对象的哈希,请参阅http://guzzle3.readthedocs.org/batching/batching.html#batching

简短的例子:

<?php

$client->send(array(
    $client->get('http://www.example.com/foo'),
    $client->get('http://www.example.com/baz'),
    $client->get('http://www.example.com/bar')
));

答案 1 :(得分:22)

与新GuzzleHttp相关的更新 guzzlehttp / guzzle

并发/并行调用现在通过几种不同的方法运行,包括Promises .. Concurrent Requests

传递RequestInterfaces数组的旧方法将不再适用。

请参阅示例此处

    $newClient = new  \GuzzleHttp\Client(['base_uri' => $base]);
    foreach($documents->documents as $doc){

        $params = [
            'language' =>'eng',
            'text' => $doc->summary,
            'apikey' => $key
        ];

        $requestArr[$doc->reference] = $newClient->getAsync( '/1/api/sync/analyze/v1?' . http_build_query( $params) );
    }

    $time_start = microtime(true);
    $responses = \GuzzleHttp\Promise\unwrap($requestArr); //$newClient->send( $requestArr );
    $time_end = microtime(true);
    $this->get('logger')->error(' NewsPerf Dev: took ' . ($time_end - $time_start) );

<强>更新: 正如@ sankalp-tambe在评论中所建议的那样,您也可以使用不同的方法来避免一组带有失败的并发请求不会返回所有响应。

虽然建议使用Pool的选项是可行的,但我仍然更喜欢承诺。

承诺的一个例子是使用结算和等待方法而不是解包。

与上述示例的区别在于

$responses = \GuzzleHttp\Promise\settle($requestArr)->wait(); 

我在下面创建了一个完整的示例,以获取有关如何处理$ response的参考。

require __DIR__ . '/vendor/autoload.php';
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Promise as GuzzlePromise;

$client = new GuzzleClient(['timeout' => 12.0]); // see how i set a timeout
$requestPromises = [];
$sitesArray = SiteEntity->getAll(); // returns an array with objects that contain a domain

foreach ($sitesArray as $site) {
    $requestPromises[$site->getDomain()] = $client->getAsync('http://' . $site->getDomain());
}

$results = GuzzlePromise\settle($requestPromises)->wait();

foreach ($results as $domain => $result) {
    $site = $sitesArray[$domain];
    $this->logger->info('Crawler FetchHomePages: domain check ' . $domain);

    if ($result['state'] === 'fulfilled') {
        $response = $result['value'];
        if ($response->getStatusCode() == 200) {
            $site->setHtml($response->getBody());
        } else {
            $site->setHtml($response->getStatusCode());
        }
    } else if ($result['state'] === 'rejected') { 
        // notice that if call fails guzzle returns is as state rejected with a reason.

        $site->setHtml('ERR: ' . $result['reason']);
    } else {
        $site->setHtml('ERR: unknown exception ');
        $this->logger->err('Crawler FetchHomePages: unknown fetch fail domain: ' . $domain);
    }

    $this->entityManager->persist($site); // this is a call to Doctrines entity manager
}

此示例代码最初发布为here

答案 2 :(得分:0)

Guzzle 6.0使发送多个异步请求变得非常容易。

有多种方法可以实现。

您可以创建异步请求,并将结果的Promise添加到单个数组,然后使用settle()方法获得结果,如下所示:

$promise1 = $client->getAsync('http://www.example.com/foo1');
$promise2 = $client->getAsync('http://www.example.com/foo2');
$promises = [$promise1, $promise2];

$results = GuzzleHttp\Promise\settle($promises)->wait();

您现在可以遍历这些结果,并使用GuzzleHttpPromiseallGuzzleHttpPromiseeach获取响应。有关更多详细信息,请参见this article

如果要发送的请求数量不确定(此处为5),则可以使用GuzzleHttp/Pool::batch()。 这是一个示例:

$client = new Client();

// Create the requests
$requests = function ($total) use($client) {
    for ($i = 1; $i <= $total; $i++) {
        yield new Request('GET', 'http://www.example.com/foo' . $i);
    }
};

// Use the Pool::batch()
$pool_batch = Pool::batch($client, $requests(5));
foreach ($pool_batch as $pool => $res) {

    if ($res instanceof RequestException) {
        // Do sth
        continue;
    }

    // Do sth
}
相关问题