eljam/circuit-breaker

PHP电路断路器

v0.2.0 2017-12-22 18:06 UTC

This package is auto-updated.

Last update: 2024-09-10 19:24:34 UTC


README

电路断路器在微服务架构中广泛用于查找微服务调用间的问题。

主要思想是保护您的代码,避免在调用的微服务不可用时进行不必要的调用。

功能

  • 自动更新。(即您无需像其他库那样手动添加成功或失败的方法)
  • 从受保护的函数返回结果
  • 重试超时
  • 排除某些异常被抛出,返回null代替。
  • 使用缓存库处理多进程更新。支持所有来自(doctrine缓存库)的缓存提供者。
  • 事件驱动

Build Status Code Quality Code Coverage SensioLabsInsight Latest Unstable Version Latest Stable Version Downloads license

完整示例

<?php

use Doctrine\Common\Cache\FilesystemCache;
use Eljam\CircuitBreaker\Breaker;
use Eljam\CircuitBreaker\Event\CircuitEvents;
use Symfony\Component\EventDispatcher\Event;

require_once __DIR__.'/vendor/autoload.php';

$fileCache  = new FilesystemCache('./store', 'txt');

//Create a circuit for github api with a file cache and we want to exclude all exception.
$breaker = new Breaker('github_api', ['ignore_exceptions' => true], $fileCache);

$breaker->addListener(CircuitEvents::SUCCESS, function (Event $event) {
    $circuit = $event->getCircuit();
    echo "Success:".$circuit->getFailures()."\n";
});

$breaker->addListener(CircuitEvents::FAILURE, function (Event $event) {
    $circuit = $event->getCircuit();
    echo "Increment failure:".$circuit->getFailures()."\n";
});

$breaker->addListener(CircuitEvents::OPEN, function (Event $event) {
    $circuit = $event->getCircuit();
    echo sprintf("circuit %s is open \n", $circuit->getName());
});

$breaker->addListener(CircuitEvents::CLOSED, function (Event $event) {
    $circuit = $event->getCircuit();
    echo sprintf("circuit %s is closed \n", $circuit->getName());
});

$breaker->addListener(CircuitEvents::HALF_OPEN, function (Event $event) {
    $circuit = $event->getCircuit();
    echo sprintf("circuit %s is half-open \n", $circuit->getName());
});

$result = $breaker->protect(function () {
    throw new \Exception("An error as occured");
    // return 'ok';
});