PHP code example of caseyamcl / guzzle_retry_middleware

1. Go to this page and download the library: Download caseyamcl/guzzle_retry_middleware library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

caseyamcl / guzzle_retry_middleware example snippets



// Per request, in the same array as other Guzzle options
$response = $client->get('/some-url', [
   'max_retry_attempts' => 5,
   'on_retry_callback'  => $notifier
]);

// When you instantiate Guzzle, in the same array as other Guzzle options
$client = new \GuzzleHttp\Client([

    // Standard Guzzle options
    'base_url'        => 'https://example.org',
    'connect_timeout' => 10.0,
    
    // Retry options
    'max_retry_attempts' => 5,
    'on_retry_callback'  => $notifier
]);

// When you instantiate the Retry middleware
$stack = \GuzzleHttp\Stack::create();
$stack->push(GuzzleRetryMiddleware::factory([
    'max_retry_attempts' => 5,
    'on_retry_callback'  => $notifier
]));



// Set the default retry attempts to 5
$client = new \GuzzleHttp\Client(['max_retry_attempts' => 5]);

// Do not retry this request
$client->get('/some/url', ['max_retry_attempts' => 0]);



$response = $client->get('/some-path', [
    'retry_on_status' => [429, 503, 500]
]);



$response = $client->get('/some-path', [
    'default_retry_multiplier' => 2.5
]);



// Custom callback to determine default timeout.  Note: $response may be NULL if a connect timeout occurred.
$response = $client->get('/some-path', [
    'default_retry_multiplier' => function($numRequests, ?ResponseInterface $response): float {
        return (float) rand(1, 5);       
    }
]);


// Retry this request if it times out:
$response = $client->get('/some-path', [
    'retry_on_timeout' => true,    // Set the retry middleware to retry when the connection or response times out
    'connect_timeout'  => 20,     // This is a built-in Guzzle option
    'timeout'          => 50      // This is also a built-in Guzzle option
]);

// You can also set these as defaults for every request:
$guzzle = new \GuzzleHttp\Client(['retry_on_timeout' => true, 'connect_timeout' => 20]);
$response = $guzzle->get('https://example.org');


use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

/**
 * Listen for retry events
 *
 * @param int                    $attemptNumber  How many attempts have been tried for this particular request
 * @param float                  $delay          How long the client will wait before retrying the request
 * @param RequestInterface       $request        Request
 * @param array                  $options        Guzzle request options
 * @param ResponseInterface|null $response       Response (or NULL if response not sent; e.g. connect timeout)
 * @param Throwable|null         $exception      This value will be present if the retry was triggered by onRejected
 *                                               (e.g. in the event of a connection timeout)                                                
 */
$listener = function(
    int $attemptNumber,
    float $delay,
    RequestInterface &$request,
    array &$options,
    ?ResponseInterface $response,
    ?Throwable $exception
) {
    
    echo sprintf(
        "Retrying request to %s.  Server responded with %s.  Will wait %s seconds.  This is attempt #%s. The error was %s",
        $request->getUri()->getPath(),
        $response->getStatusCode(),
        number_format($delay, 2),
        $attemptNumber,
        $exception->getMessage()
    );
}

$client = new \GuzzleHttp\Client([
    'on_retry_callback' => $listener
]);

$response = $client->get('/some/path');


$stack = \GuzzleHttp\Stack::create();
$stack->push(GuzzleRetryMiddleware::factory(['max_retry_attempts' => 5]));
$client = new \GuzzleHttp\Client(['handler' => $stack]);

// Retry will NOT be attempted for this request..
$client->get('https://example.org', ['retry_enabled' => false]);

// Retry WILL be attempted for this request...
$client->get('https://example.org');

// Retry this request if it times out:
$response = $client->get('/some-path', [
    'expose_retry_header' => true  // This adds the 'X-Retry-Counter' if a request was retried
]);

// If a request was retried, the response will 

// Retry this request if it times out:
$response = $client->get('/some-path', [
    'expose_retry_header' => true,
    'retry_header'        => 'X-Retry-Count'
]);

// If a request was retried, the response will 

// Change the name of the expected retry after header to something else:
$response = $client->get('/some-path', [
    'retry_after_header' => 'X-Custom-Retry-After-Seconds'
]);

// Otherwise, the default `Retry-After` header will be used.
$response = $client->get('/some-path');

// Set the maximum allowable timeout
// If the calculated value exceeds 120 seconds, then just return 120 seconds
$response = $client->get('/some-path', [
    'max_allowable_timeout_secs' => 120
]);

// This will fail when either the number of seconds is reached, or the number of retry attempts is reached, whichever
// comes first 
$response = $client->get('/some-path', [
    'max_retry_attempts' => 10 
    'give_up_after_secs' => 10
]);

//
$response = $client->get('/some-path', [
    'retry_on_methods' => ['GET', 'OPTIONS', 'HEAD']
]);

use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;


$callback = function (array $options, ?ResponseInterface $response, RequestInterface $request): bool {
    // Only allow retries if x-header header is set
    if(! $request->hasHeader('x-header')) {
        return false; 
    }

    // Response will be NULL in the event of a connection timeout, so your callback function
    // will need to be able to handle that case
    if (! $response) {
        return true;
    }

    // Get the HTTP body as a string
    $body = (string) $response->getBody();
    return str_contains($body, 'error'); // NOTE: The str_contains function is available only in PHP 8+ 
};

$response = $client->get('/some-path', [
    // ..other options..,
   'should_retry_callback' => $callback
]);