30

Circuit Breaker Pattern in PHP

 4 years ago
source link: https://www.tuicool.com/articles/ZryAZvE
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Circuit Breaker PHP is a package by Leonardo Carmo which implements the Circuit breaker design pattern using Redis as the backend.

If you are not familiar with this pattern or want to learn more, check out Martin Fowler’s CircuitBreaker article.

The package provides a Redis adapter (using the PHP Redis module) that follows an interface, meaning you can create different adapters to work with this Circuit Breaker package.

Here’s an example from the readme of setting up an instance of the Circuit Breaker using the provided Redis adapter:

use LeoCarmo\CircuitBreaker\CircuitBreaker;

// Connect to redis
$redis = new \Redis();
$redis->connect('localhost', 6379);

$adapter = new \LeoCarmo\CircuitBreaker\Adapters\RedisAdapter($redis, 'my-product');

// Set redis adapter for CB
CircuitBreaker::setAdapter($adapter);

Here’s a basic example of some of the things you can do with this library:

// Check circuit status for service: `my-service`
if (! CircuitBreaker::isAvailable('my-service')) {  
  die('Circuit is not available!');  
}

// Usage example for success and failure  
try {  
  Service::execute('something');  
  CircuitBreaker::success('my-service');  
} catch (\ServiceException $e) {  
  CircuitBreaker::failure('my-service');  
  die($e->getMessage());  
}

You can learn more about this package, get full installation instructions, and view the source code on GitHub at leocarmo/circuit-breaker-php .

Filed in: News


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK