承接 algoyounes/circuit-breaker 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

algoyounes/circuit-breaker

Composer 安装命令:

composer require algoyounes/circuit-breaker

包简介

Circuit Breaker is laravel package that provides a way to handle failures gracefully

README 文档

README

Circuit Breaker Logo

Build Status Total Downloads Latest Stable Version License

Circuit Breaker is a Laravel package that provides a simple and efficient way to manage service calls and prevent cascading failures. It lets you define custom callbacks for key circuit states and run operations with circuit breaker logic.

The following diagram illustrates how the Circuit Breaker Pattern works:

circuit-breaker.png

For more info, check the official pattern doc here.

Table of Contents

Prerequisites

This package requires:

  • PHP 8.2+
  • Laravel 11+
  • A configured Laravel cache driver

Installation

You can install the package via Composer:

composer require algoyounes/circuit-breaker

You can publish the configuration file using the following command:

php artisan vendor:publish --provider="AlgoYounes\CircuitBreaker\Providers\CircuitBreakerServiceProvider" --tag="config"

Usage

You can manage specific services with granular control using the forService(...) method. the service-name parameter is a unique identifier key for your service, ensuring its circuit breaker configuration is isolated from other services.

$circuit = $this->circuitManager->forService('service-name');

Tip

Use the unique service-name key across your application to consistently reference the same circuit configuration (e.g., 'payment-service', ...)

Custom Callbacks

You can define callbacks for key circuit states:

Callback Description Parameters Received
onOpen Triggered when the circuit goes into OPEN, blocking calls to prevent further failures CircuitTransition
onHalfOpen The circuit enters HALF-OPEN to test stability, letting one request through CircuitTransition
onClose The circuit returns to CLOSED, allowing all requests without restrictions CircuitTransition
onSuccess Fires when a request succeeds, indicating system availability CircuitResult, CircuitTransition
onFailure Triggered when a request fails, potentially opening the circuit CircuitResult, CircuitTransition
onSteadyState Indicates the circuit is stable, with no need for changes CircuitTransition

Example of defining callbacks:

$circuit->onOpen(function (CircuitTransition $circuitTransition) { 
    // Your custom logic here
});

$circuit->onSuccess(function (CircuitResult $circuitResult, CircuitTransition $circuitTransition) {
    // Your custom logic here
});

// Params passed are optional

Running an Operation

To run an operation and manage its state through the circuit breaker, use the run method:

$circuit->run(function () {
    // Your service call here
});
// or
$circuit->run($this->serviceName->create(...));

This will execute the provided closure, applying the circuit breaker logic (e.g., open, half-open, closed states) around the service call.

Note

If you prefer a more direct approach, you can create a CircuitBuilder instance:

$circuit = CircuitBuilder::make('service-name')

Simplified Operation

For a simplified approach, use the run method directly from CircuitManager:

$this->circuitManager->run('service-name', function () {
    // Your service call here
});
// or
$this->circuitManager->run('service-name', $this->serviceName->create(...));

Guzzle Middleware Integration

The package provides a Guzzle middleware to automatically manage circuit breaker logic for HTTP requests.

To enable the middleware, add the following to your Guzzle client configuration:

use AlgoYounes\CircuitBreaker\Middleware\GuzzleMiddleware;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

$stack = HandlerStack::create();
$stack->push(GuzzleMiddleware::create());

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

$response = $client->get('https://api.example.com', [
    'headers' => [
        'X-Circuit-Key' => 'service-name',
    ],
]);

Laravel Http Facade Integration

The package integrates with Laravel's built-in Http facade out of the box:

use Illuminate\Support\Facades\Http;

$response = Http::withCircuitBreaker('payment-service')
    ->get('https://api.payment.com/charge', [
        'amount' => 1000,
    ]);

This automatically applies the circuit breaker middleware to the request using payment-service as the circuit key. You can chain it with any Http method:

$response = Http::withCircuitBreaker('shipping-service')
    ->withToken($apiToken)
    ->timeout(10)
    ->post('https://api.example.com/track', $payload);

When the circuit is open, a RejectedException is thrown:

use AlgoYounes\CircuitBreaker\Guzzle\Exceptions\RejectedException;

try {
    $response = Http::withCircuitBreaker('payment-service')
        ->get('https://api.example.com/charge');
} catch (RejectedException $e) {
    // Circuit is open — handle gracefully (e.g., return cached response, queue for retry)
}

How It Works

State Transitions

The circuit breaker operates in three states:

    ┌──────────────────────────────────────────────────────┐
    │                                                      │
    ▼                                                      │
 CLOSED ──── failures ≥ threshold ────► OPEN               │
 (normal)                               (all requests      │
                                         rejected)         │
                                           │               │
                                    cooldown expires       │
                                           │               │
                                           ▼               │
                                       HALF-OPEN           │
                                      (single probe)       │
                                        │       │          │
                                   success    failure      │
                                        │       │          │
                                        │       └──► OPEN  │
                                        │                  │
                                        └──────────────────┘
  • CLOSED — Normal operation. All requests pass through. Failures are counted.
  • OPEN — The service is considered down. All requests are rejected immediately without calling the service. After the cooldown_period expires, the circuit moves to HALF-OPEN.
  • HALF-OPEN — A single probe request is sent to test the service. If it succeeds, the circuit closes. If it fails, the circuit re-opens.

Half-Open State Behavior

When a circuit transitions from OPEN to HALF-OPEN, this package uses a single-probe approach — only one request is allowed to test the recovering service at a time. All other concurrent requests are rejected immediately until the probe completes.

OPEN (cooldown expired)
  │
  ├── Request A → probes service → success → CLOSED (all traffic resumes)
  ├── Request B → rejected (fail-fast)
  ├── Request C → rejected (fail-fast)
  └── ...
  • If the probe succeeds, the circuit closes and normal traffic resumes.
  • If the probe fails, the circuit re-opens and a new cooldown period begins.

What your code receives when a request is rejected:

  • Via run() — returns a CircuitResult where isSuccess() and isAvailable() both return false
  • Via Http::withCircuitBreaker() or Guzzle middleware — throws RejectedException

Configuration

After publishing the config file, you can adjust these settings in config/circuit-breaker.php:

Option Default Description
enabled true Enable or disable the circuit breaker globally
defaults.failure_threshold 5 Number of failures before the circuit opens
defaults.cooldown_period 60 Seconds to wait before transitioning from OPEN to HALF-OPEN
defaults.success_threshold 1 Successful probes needed in HALF-OPEN to close the circuit
cache.ttl 86400 Cache entry lifetime in seconds
cache.prefix circuit-breaker Prefix for cache keys
cache.store default Laravel cache store to use

You can also override settings per service:

'services' => [
    'payment-service' => [
        'failure_threshold' => 10,
        'cooldown_period'   => 120,
        'success_threshold' => 3,
    ],
],

Contributing

Thank you for considering contributing to the Circuit Breaker package! Please check the CONTRIBUTING file for more details.

License

The Circuit Breaker package is open-sourced software licensed under the MIT license.

algoyounes/circuit-breaker 适用场景与选型建议

algoyounes/circuit-breaker 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4.7k 次下载、GitHub Stars 达 59, 最近一次更新时间为 2026 年 03 月 14 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「circuit breaker」 「laravel circuit breaker」 「php circuit breaker」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 algoyounes/circuit-breaker 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 algoyounes/circuit-breaker 我们能提供哪些服务?
定制开发 / 二次开发

基于 algoyounes/circuit-breaker 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 4.7k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 59
  • 点击次数: 17
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 59
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-14