PHP code example of leocarmo / circuit-breaker-php
1. Go to this page and download the library: Download leocarmo/circuit-breaker-php 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/ */
leocarmo / circuit-breaker-php example snippets
use LeoCarmo\CircuitBreaker\CircuitBreaker;
use LeoCarmo\CircuitBreaker\Adapters\RedisAdapter;
// Connect to redis
$redis = new \Redis();
$redis->connect('localhost', 6379);
$adapter = new RedisAdapter($redis, 'my-product');
// Set redis adapter for CB
$circuit = new CircuitBreaker($adapter, 'my-service');
use LeoCarmo\CircuitBreaker\CircuitBreaker;
use LeoCarmo\CircuitBreaker\Adapters\RedisClusterAdapter;
// Connect to redis
$redis = new \Redis();
$redis->connect('localhost', 6379);
$adapter = new RedisClusterAdapter($redis, 'my-product');
// Set redis adapter for CB
$circuit = new CircuitBreaker($adapter, 'my-service');
use LeoCarmo\CircuitBreaker\CircuitBreaker;
$circuit = new CircuitBreaker(new SwooleTableAdapter(), 'my-service');
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use LeoCarmo\CircuitBreaker\GuzzleMiddleware;
$handler = new GuzzleMiddleware($circuit);
$handlers = HandlerStack::create();
$handlers->push($handler);
$client = new Client(['handler' => $handlers]);
$response = $client->get('leocarmo.dev');
$handler = new GuzzleMiddleware($circuit);
$handler->setCustomSuccessCodes([400]);
$handler = new GuzzleMiddleware($circuit);
$handler->setCustomIgnoreCodes([412]);
$circuit->setSettings([
'timeWindow' => 60, // Time for an open circuit (seconds)
'failureRateThreshold' => 50, // Fail rate for open the circuit
'intervalToHalfOpen' => 30, // Half open time (seconds)
]);
// Check circuit status for service
if (! $circuit->isAvailable()) {
die('Circuit is not available!');
}
// Usage example for success and failure
try {
myService();
$circuit->success();
} catch (RuntimeException $e) {
// If an error occurred, it must be recorded as failure.
$circuit->failure();
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.