Skip to content

Instantly share code, notes, and snippets.

@jacksontong
Last active June 8, 2018 03:03
Show Gist options
  • Save jacksontong/e42cc6a916b5da4a3f1f015e9952495c to your computer and use it in GitHub Desktop.
Save jacksontong/e42cc6a916b5da4a3f1f015e9952495c to your computer and use it in GitHub Desktop.
Guzzle async example
<?php
require_once('vendor/autoload.php');
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Promise as GuzzlePromise;
//https://stackoverflow.com/a/32751004/3787302
$start_time = microtime(TRUE);
$client = new GuzzleClient(['timeout' => 12.0]); // see how i set a timeout
$requestPromises = [];
$sitesArray = [
'http://vnexpress.net',
'http://google.vn',
'http://bbc.com'
];
foreach ($sitesArray as $k => $site) {
$requestPromises[$k] = $client->getAsync($site);
}
$results = GuzzlePromise\settle($requestPromises)->wait();
foreach ($results as $domain => $result) {
$site = $sitesArray[$domain];
if ($result['state'] === 'fulfilled') {
/** @var \GuzzleHttp\Psr7\Response $response */
$response = $result['value'];
if ($response->getStatusCode() == 200) {
var_dump($response->getBody());
echo '<br><hr>';
} else {
var_dump($response->getStatusCode());
}
} else if ($result['state'] === 'rejected') {
// notice that if call fails guzzle returns is as state rejected with a reason.
echo 'ERR: ' . var_dump($result['reason']);
} else {
echo 'ERR: unknown exception ';
}
}
$end_time = microtime(TRUE);
echo $end_time - $start_time . "<br><hr>";
$start_time = microtime(TRUE);
foreach ($sitesArray as $item) {
$client->request('GET', $item);
}
$end_time = microtime(TRUE);
echo $end_time - $start_time . "<br><hr>";
@chienlvneoscorp
Copy link

Thank you so much (y)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment