leocarmo/circuit-breaker-php

PHP 电路断路器

5.0.0 2022-12-14 17:53 UTC

This package is auto-updated.

Last update: 2024-09-06 15:48:19 UTC


README

Build Status Scrutinizer Code Quality Code Intelligence Status Total Downloads

有关此模式的更多信息,请参阅 这里

从 composer 开始

composer require leocarmo/circuit-breaker-php

适配器

Redis 适配器

第一个参数是 Redis 连接,第二个参数是你的产品名称,为了 Redis 命名空间避免与其他使用相同 Redis 的产品发生键冲突。

use LeoCarmo\CircuitBreaker\CircuitBreaker;
use LeoCarmo\CircuitBreaker\Adapters\RedisAdapter;

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

$adapter = new RedisAdapter($redis, 'my-product');

// Set redis adapter for CB
$circuit = new CircuitBreaker($adapter, 'my-service');

请参阅 此示例 以获取完整示例

Redis 集群适配器

不使用 multi 命令。第一个参数是 Redis 连接,第二个参数是你的产品名称,为了 Redis 命名空间避免与其他使用相同 Redis 的产品发生键冲突。

use LeoCarmo\CircuitBreaker\CircuitBreaker;
use LeoCarmo\CircuitBreaker\Adapters\RedisClusterAdapter;

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

$adapter = new RedisClusterAdapter($redis, 'my-product');

// Set redis adapter for CB
$circuit = new CircuitBreaker($adapter, 'my-service');

请参阅 此示例 以获取完整示例

SwooleTable 适配器

use LeoCarmo\CircuitBreaker\CircuitBreaker;

$circuit = new CircuitBreaker(new SwooleTableAdapter(), 'my-service');

Guzzle 中间件

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use LeoCarmo\CircuitBreaker\GuzzleMiddleware;

$handler = new GuzzleMiddleware($circuit);

$handlers = HandlerStack::create();
$handlers->push($handler);

$client = new Client(['handler' => $handlers]);

$response = $client->get('leocarmo.dev');

重要:所有介于 200 到 299 之间的状态码都将记录为成功,其他状态码将记录为失败。

请参阅 此示例 以获取完整示例

自定义成功状态码

如果您需要指定一个不是失败的自定义状态码,可以使用

$handler = new GuzzleMiddleware($circuit);
$handler->setCustomSuccessCodes([400]);

重要:此配置将在返回状态码 400 时记录成功

请参阅 此示例 以获取完整示例

忽略状态码

如果您想忽略返回的状态码,并不仅记录成功或失败,请使用此方法

$handler = new GuzzleMiddleware($circuit);
$handler->setCustomIgnoreCodes([412]);

重要

要使用“自定义成功状态码”或“忽略状态码”,您必须设置 Guzzle 客户端配置 http_errors = false,因为当状态码不在范围 >200 && <300 时,Guzzle 客户端会抛出 ClientExceptionServerException

设置电路断路器设置

这不是必需的,将设置默认值

$circuit->setSettings([
    'timeWindow' => 60, // Time for an open circuit (seconds)
    'failureRateThreshold' => 50, // Fail rate for open the circuit
    'intervalToHalfOpen' => 30,  // Half open time (seconds)
]);

检查电路是否可用(关闭)

每次检查都是针对特定服务。因此,您可以在同一应用程序中具有多个服务,当一个电路打开时,其他电路正常工作。

// Check circuit status for service
if (! $circuit->isAvailable()) {
    die('Circuit is not available!');
}

记录成功和失败

// Usage example for success and failure  
try {
    myService();
    $circuit->success();
} catch (RuntimeException $e) {
    // If an error occurred, it must be recorded as failure.
    $circuit->failure();
}

开发

设置

make setup

测试

make test 

贡献者