1. Go to this page and download the library: Download postcon/resilience 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/ */
postcon / resilience example snippets
$redis = new \Redis();
$circuitBreaker = new \Postcon\Resilience\RedisCircuitBreaker($redis, 'system', 120, 3);
$circuitBreaker->reportSuccess();
$circuitBreaker->isAvailable(); // should be true
$circuitBreaker->reportFailure();
$circuitBreaker->isAvailable(); // ... still true
$circuitBreaker->reportFailure();
$circuitBreaker->isAvailable(); // ... still true
$circuitBreaker->reportFailure();
$circuitBreaker->isAvailable(); // ... now it is false
$circuitBreaker->check(); // throws CircuitBreakerTripped exception, if 'system' is not available.
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\ServerException;
use Postcon\Resilience\CircuitBreakerInterface;
use Postcon\Resilience\CircuitBreakerTripped;
use Psr\Http\Message\RequestInterface;
class CircuitBreakerClientDecorator implements ClientInterface
{
/** @var ClientInterface */
private $baseClient;
/** @var CircuitBreakerInterface */
private $circuitBreaker;
public function __construct(ClientInterface $baseClient, CircuitBreakerInterface $circuitBreaker)
{
$this->baseClient = $baseClient;
$this->circuitBreaker = $circuitBreaker;
}
/**
* @inheritdoc
*
* @throws CircuitBreakerTripped
*/
public function send(RequestInterface $request, array $options = [])
{
return $this->check(function () use ($request, $options) {
$this->baseClient->send($request, $options);
});
}
// ...
/**
* @throws GuzzleException
* @throws CircuitBreakerTripped
*/
private function check(callable $function)
{
$this->circuitBreaker->check();
try {
$result = $function();
$this->circuitBreaker->reportSuccess();
return $result;
} catch (ConnectException $e) {
$this->circuitBreaker->reportFailure();
throw $e;
} catch (ServerException $e) {
$this->circuitBreaker->reportFailure();
throw $e;
} catch (ClientException $e) {
$this->circuitBreaker->reportSuccess();
throw $e;
}
}
}