francescomalatesta/laravel-circuit-breaker

Laravel 框架的断路器模式实现

0.1.0 2018-04-21 15:00 UTC

This package is auto-updated.

Last update: 2024-09-19 09:10:17 UTC


README

Laravel Framework 5.6 的断路器模式实现。

Latest Version on Packagist Software License Build Status Quality Score StyleCI

如果您需要为 Laravel 应用程序轻松实现 断路器模式,您就来到了正确的位置。

注意:此包与 Laravel 5.6 兼容。其他/旧版本尚未进行测试。

安装

您可以使用 Composer 为您的项目安装此包。

$ composer require francescomalatesta/laravel-circuit-breaker

无需担心服务提供者和外观:Laravel 可以自动发现该包而无需任何操作!

只需记住使用以下命令 发布配置文件

php artisan vendor:publish

用法

您将始终使用单个类(CircuitBreaker 外观或 CircuitBreakerManager 类,如果您想注入它)来与此包一起工作。

以下是方法参考

isAvailable(string $identifier) : bool

如果 $identifier 服务当前可用,则返回 true。否则返回 false

注意:您可以使用任何您想要的标识符。我尽可能喜欢使用 MyClass::class 名称。

reportFailure(string $identifier) : void

报告 $identifier 服务的失败尝试。请参阅下面的配置部分,了解如何管理尝试和失败次数。

reportSuccess(string $identifier) : void

报告 $identifier 服务的成功尝试。您可以使用它将服务标记为可用,并从它中删除“失败”状态。

配置

默认值

通过编辑 config/circuit_breaker.php 配置文件内容,您可以以更适合您需求的方式调整断路器。

default 项下有三个值

<?php

return [
    'defaults' => [
        'attempts_threshold' => 3,
        'attempts_ttl' => 1,
        'failure_ttl' => 5
    ],
    
    // ...
];
  • attempts_threshold:用于指定在声明服务“失败”之前需要尝试多少次 - 默认:3;
  • attempts_ttl:用于指定在声明服务“失败”之前进行尝试的时间(以分钟为单位)窗口 - 默认:1;
  • failure_ttl:一旦服务被标记为“失败”,它将保持此状态这么多分钟 - 默认:5;

为了更好地理解:默认情况下,1 分钟内 3 次失败尝试将导致服务“失败” 5 分钟。

服务映射

调整配置文件很酷,但如果我需要为特定服务具有特定的 TTL 和尝试次数怎么办?没问题:这里有一个 services 选项来帮助。

config/circuit_breaker.php 配置文件中所示,您还有一个 services 项。您可以在其中指定单个服务的设置。以下是一个示例

<?php

return [
    'defaults' => [
        'attempts_threshold' => 3,
        'attempts_ttl' => 1,
        'failure_ttl' => 5
    ],
    
    'services' => [
        'my_special_service_identifier' => [
            'attempts_threshold' => 2,
            'attempts_ttl' => 1,
            'failure_ttl' => 10
        ]
    ]
];

然后,当您调用 CircuitBreaker::reportFailure('my_special_service_identifier') 时,断路器将识别“特殊”服务并使用特定的配置设置、TTL 和尝试次数。

技巧:您还可以在 service 数组中 覆盖 单个服务的单个设置。其他将合并到默认值中。

用法示例

假设我们的应用程序已经集成了支付网关。我们将这个类称为PaymentsGateway

现在,假设这是一个第三方服务:有时候它可能会关闭一段时间。然而,我们不想阻止用户购买东西,所以如果PaymentsGateway服务不可用,我们希望将订单重定向到名为DelayedPaymentsGateway的备用服务,该服务将简单地“排队”延迟订单以在未来处理。

让我们在下面的BuyArticleOperation类中模拟这个过程。

<?php

class BuyArticleOperation {
    
    /** @var PaymentsGateway */
    private $paymentsGateway;
    
    /** @var DelayedPaymentsGateway */
    private $delayedPaymentsGateway;
    
    public function process(string $orderId)
    {
       // doing stuff with my order and then...
       
       try {
           $this->paymentsGateway->attempt($orderId);
       } catch (PaymentsGatewayException $e) {
           // something went wrong, let's switch the payment
           // to the "delayed" queue system
           $this->delayedPaymentsGateway->queue($orderId);
       }
    }
}

太好了!现在我们100%确信我们的支付将会被处理。有时候这还不够。

你知道吗?PaymentsGateway可能需要至少5秒钟才能完成单次尝试,而你的应用程序每分钟接收数百个订单。即使我们知道在第一次尝试后它不起作用,反复调用PaymentsGateway真的有帮助吗?

这就是如何使用这个熔断器来编写你的代码。

<?php

use CircuitBreaker;
use My\Namespace\PaymentsGateway;
use My\Namespace\DelayedPaymentsGateway;

class BuyArticleOperation {
    
    /** @var PaymentsGateway */
    private $paymentsGateway;
    
    /** @var DelayedPaymentsGateway */
    private $delayedPaymentsGateway;
    
    public function process(string $orderId)
    {
        if(CircuitBreaker::isAvailable(PaymentsGateway::class)) {
            try {
                $this->paymentsGateway->attempt($orderId);
            } catch (PaymentsGatewayException $e) {
                // something went wrong, let's switch the payment
                // to the "delayed" queue system and report that
                // the default gateway is not working!
                $this->delayedPaymentsGateway->queue($orderId);
                CircuitBreaker::reportFailure(PaymentsGateway::class);
            }
            
            // there's nothing we can do here anymore
            return;
        }
        
        // we already know that the service is disabled, so we
        // can queue the payment process on the delayed queue
        // directly, without letting our users wait more
        $this->delayedPaymentsGateway->queue($orderId);
    }
}

假设我们在10秒内处理了100个订单(在不同的进程中)。

  • 对于第一个订单,我们让PaymentsGateway处理,但出了点问题;
  • 我们在DelayedPaymentsGateway上排队支付,并向CircuitBreaker报告失败;
  • 第二和第三个订单也是这样;
  • 在第三个订单处理完毕后,CircuitBreaker决定,在3次尝试(不到1分钟内)后,可以宣布PaymentsGateway“失败”,我们可以直接使用我们的DelayedPaymentsGateway备用服务一段时间(5分钟);
  • 剩余的97个订单被排队并成功处理,没有浪费时间(97 * 5 = 485处理秒)在一个我们相当确定不会工作的服务上;

酷吧? :)

测试

你可以轻松地执行以下测试

$ vendor/bin/phpunit

即将推出

  • 指数退避失败TTLs;
  • 设置小于1分钟的TTLs;
  • 使底层存储实现可定制;

贡献

请参阅CONTRIBUTINGCODE_OF_CONDUCT以获取详细信息。

安全性

如果你发现任何安全问题,请通过电子邮件francescomalatesta@live.it而不是使用问题跟踪器。

致谢

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件