Skip to content

Instantly share code, notes, and snippets.

@simodima
Last active August 27, 2018 20:27
Show Gist options
  • Save simodima/8ecb36ce124572841cfd8a97a46bada2 to your computer and use it in GitHub Desktop.
Save simodima/8ecb36ce124572841cfd8a97a46bada2 to your computer and use it in GitHub Desktop.
<?php
class CircuitBreaker
{
private $maxFailures;
private $service;
private $redisClient;
public function __construct(int $maxFailures, callable $service)
{
$this->maxFailures = $maxFailures;
$this->service = $service;
$this->redisClient = new RedisClient();
}
private function isUp(string $key)
{
return (int)$this->redisClient->get($key) < $this->maxFailures;
}
private function fail(string $key, int $ttl)
{
$this->redisClient->incr($key, 1);
$this->redisClient->expire($key, $ttl);
}
public function __invoke()
{
[$arguments, $defaultResponse] = func_get_args();
$key = md5($arguments);
if (!$this->isUp($key)) {
return $defaultResponse;
}
try {
$result = call_user_func_array($this->service, $arguments);
return $result;
} catch (\Throwable $e) {
$this->fail($key, 10);
return $defaultResponse;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment