Skip to content

Instantly share code, notes, and snippets.

@gunnarlium
Created December 17, 2015 16:23
Show Gist options
  • Save gunnarlium/665fc1a2f6dd69dfba65 to your computer and use it in GitHub Desktop.
Save gunnarlium/665fc1a2f6dd69dfba65 to your computer and use it in GitHub Desktop.
Example of how to create a retry subscriber for Guzzle 6
<?php
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Request as Psr7Request;
use GuzzleHttp\Psr7\Response as Psr7Response;
use Psr\Log\LoggerInterface;
const MAX_RETRIES = 2;
require_once __DIR__ . '/../vendor/autoload.php';
/**
* @param LoggerInterface $logger
* @return Client
*/
function createHttpClient(LoggerInterface $logger)
{
$stack = HandlerStack::create(new CurlHandler());
$stack->push(\GuzzleHttp\Middleware::retry(createRetryHandler($logger)));
$client = new Client([
'handler' => $stack,
]);
return $client;
}
function createRetryHandler(LoggerInterface $logger)
{
return function (
$retries,
Psr7Request $request,
Psr7Response $response = null,
RequestException $exception = null
) use ($logger) {
if ($retries >= MAX_RETRIES) {
return false;
}
if (!(isServerError($response) || isConnectError($exception))) {
return false;
}
$logger->warning(sprintf(
'Retrying %s %s %s/%s, %s',
$request->getMethod(),
$request->getUri(),
$retries + 1,
MAX_RETRIES,
$response ? 'status code: ' . $response->getStatusCode() : $exception->getMessage()
), [$request->getHeader('Host')[0]]);
return true;
};
}
/**
* @param Psr7Response $response
* @return bool
*/
function isServerError(Psr7Response $response = null)
{
return $response && $response->getStatusCode() >= 500;
}
/**
* @param RequestException $exception
* @return bool
*/
function isConnectError(RequestException $exception = null)
{
return $exception instanceof ConnectException;
}
@fer-ri
Copy link

fer-ri commented Jan 8, 2017

You need to put your blog url in here for detail 👍

https://addshore.com/2015/12/guzzle-6-retry-middleware/

@userlond
Copy link

userlond commented Aug 2, 2018

I use retry handler from this snippet.

I need to know somehow what url was rejected because of retry count limit. I.e. I need to call rejected callback when retry count was exceeded:

<?php
$requests = function () {
    // links yielding
};

$stack = \GuzzleHttp\HandlerStack::create();
// push retry middleware somehos
// and init client

$poolConfig = [
    'fulfilled' => function (\GuzzleHttp\Psr7\Response $response, $index) {
    },
    'rejected' => function ($reason, $index) {
    }
];

/**
 * @var \GuzzleHttp\Client $client
 */
$pool = new \GuzzleHttp\Pool($client, $requests(), $poolConfig);
$promise = $pool->promise();
$promise->wait();

Does somebody know how to solve the problem?

@andreshg112
Copy link

How can I add a sleep for retrying? Like this?

$logger->warning(sprintf(
            'Retrying %s %s %s/%s, %s',
            $request->getMethod(),
            $request->getUri(),
            $retries + 1,
            MAX_RETRIES,
            $response ? 'status code: ' . $response->getStatusCode() : $exception->getMessage()
        ), [$request->getHeader('Host')[0]]);

        sleep(1);

        return true;

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