webfan3/php-easy-breaker

PHP 断路器

v0.3.6 2022-09-06 20:42 UTC

This package is auto-updated.

Last update: 2024-09-07 00:47:50 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';
});