Skip to content

Instantly share code, notes, and snippets.

@Diego81
Created May 4, 2018 10:05
Show Gist options
  • Save Diego81/8ac2eb65ebb7f8c65830755101893ff9 to your computer and use it in GitHub Desktop.
Save Diego81/8ac2eb65ebb7f8c65830755101893ff9 to your computer and use it in GitHub Desktop.
Guzzle Http client retry
require './vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
class TestRetry {
public function test()
{
$handlerStack = HandlerStack::create(new CurlHandler());
$handlerStack->push(Middleware::retry($this->retryDecider(), $this->retryDelay()));
$client = new Client(array('handler' => $handlerStack));
$response = $client->request(
'GET',
// @todo replace to a real url!!!
'https://500-error-code-url'
)->getBody()->getContents();
return \GuzzleHttp\json_decode($response, true);
}
public function retryDecider()
{
return function (
$retries,
Request $request,
Response $response = null,
RequestException $exception = null
) {
// Limit the number of retries to 5
if ($retries >= 5) {
return false;
}
// Retry connection exceptions
if ($exception instanceof ConnectException) {
return true;
}
if ($response) {
// Retry on server errors
if ($response->getStatusCode() >= 500 ) {
return true;
}
}
return false;
};
}
/**
* delay 1s 2s 3s 4s 5s
*
* @return Closure
*/
public function retryDelay()
{
return function ($numberOfRetries) {
return 1000 * $numberOfRetries;
};
}
}
$TestRetry = new TestRetry();
$TestRetry->test();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment