endisha/resilient-client
Composer 安装命令:
composer require endisha/resilient-client
包简介
Resilient Client is a PHP package designed to implement a circuit breaker pattern to enhance stability and prevent cascading failure requests
README 文档
README
Resilient Client is a PHP package designed to implement a circuit breaker pattern to enhance stability and prevent cascading failure requests.
What is circuit breaker pattern?
The Circuit Breaker is a design pattern used in software development. It is used to detect and prevent cascading request failures due to slow network connectivity, timeouts, unavailability, or unexpected system difficulties.
Requirements
- PHP ^8.1 or higher
Installation
You can install the package via Composer by running the following command:
composer require endisha/resilient-client
Usage
To use the package in your project, include the Composer autoload file:
require_once __DIR__ . '/vendor/autoload.php';
Implementing the circuit breaker pattern:
use ResilientClient\CircuitBreaker; use ResilientClient\CircuitBreaker\Adapters\FileStorageAdapter; $adapter = new FileStorageAdapter; $adapter->setPath(__DIR__ . '/storage/'); $circuitBreaker = new CircuitBreaker($adapter); // The maximum number of consecutive failures that can occur before the circuit breaker trips and enters a [failed] state $circuitBreaker->setFailureThreshold(3); // The duration that the circuit breaker waits in an [open] state before allowing test requests to determine if the service has recovered (In seconds) $circuitBreaker->setResetTimeout(300);
The CircuitBreaker constructor also allows setting a custom key as the second parameter; the default value is default
$circuitBreaker = new CircuitBreaker($adapter, 'github-cb');
Adapters
The package supports two types of adapters, each serving as a method of state storage for the circuit breaker pattern:
- File Storage Adapter: Stores states within files.
- PDO Database Adapter: Uses PDO to store states in a database.
File Storage Adapter
To use the File Storage Adapter and save circuit states to files use FileStorageAdapter and follow these steps:
use ResilientClient\CircuitBreaker\Adapters\FileStorageAdapter; $adapter = new FileStorageAdapter; $adapter->setPath('path/to/storage');
Database (PDO) Adapter
To use the Database (PDO) Adapter and work with PDO to save states in the circuit_breaker table, you need to create the custom table first:
CREATE TABLE `circuit_breaker` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `key` varchar(40) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `state` varchar(40) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `failure_count` int(11) NOT NULL, `last_failure_time` int(11) DEFAULT NULL, `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Create an instance of PDODatabaseAdapter class
use ResilientClient\CircuitBreaker\Adapters\PDODatabaseAdapter; use PDO; // PDO connection $pdo = new PDO("mysql:host=localhost;dbname=name", 'user', 'pass'); // Use PDODatabaseAdapter $adapter = new PDODatabaseAdapter($pdo); $adapter->setTable('circuit_breaker'); //table: circuit_breaker
How it Works
- To check if the circuit is open (not available), use:
$circuit->isNotAvaiable();
- To mark a request as successful:
$circuit->success();
- To mark a request as failed:
$circuit->failure();
Example
use ResilientClient\CircuitBreaker\Adapters\FileStorageAdapter; use ResilientClient\CircuitBreaker\CircuitBreaker; use ResilientClient\CircuitBreaker\Exceptions\CircuitBreakerException; $adapter = new FileStorageAdapter; $adapter->setPath(__DIR__ . '/storage/'); $circuitBreaker = new CircuitBreaker($adapter); $circuitBreaker->setFailureThreshold(3); $circuitBreaker->setResetTimeout(300); try { if ($circuitBreaker->isNotAvailable()) { throw new CircuitBreakerException('Service is unreachable'); } // Send request // .... $successRequest = true; // .... if ($successRequest) { $circuitBreaker->success(); } else { $circuitBreaker->failure(); } } catch (\CircuitBreakerException $e) { echo $e->getMessage(); }
Guzzle Integration
The package supports integration with Guzzle through the CircuitBreakerGuzzleMiddleware middleware. This middleware is automatically implemented when ConnectException exceptions are thrown due to problems connecting to remote servers or establishing connections. To implement it, follow these steps:
use GuzzleHttp\Client; use GuzzleHttp\Handler\CurlHandler; use GuzzleHttp\HandlerStack; use ResilientClient\CircuitBreaker\Middleware\CircuitBreakerGuzzleMiddleware; $stack = HandlerStack::create(new CurlHandler()); $middleware = new CircuitBreakerGuzzleMiddleware($circuitBreaker); $stack->push($middleware); $args['handler'] = $stack; $client = new Client($args); // etc..
Additionally, you can specify certain HTTP status codes as failure requests. For example, you might want to treat errors like 301 (Moved Permanently) and 302 (Found) as failure responses:
use GuzzleHttp\Client; use GuzzleHttp\Handler\CurlHandler; use GuzzleHttp\HandlerStack; use ResilientClient\CircuitBreaker\Middleware\CircuitBreakerGuzzleMiddleware; $stack = HandlerStack::create(new CurlHandler()); $middleware = new CircuitBreakerGuzzleMiddleware($circuitBreaker); $middleware->setAsFailureRequestCodes(301, 302); $stack->push($middleware); $args['handler'] = $stack; $client = new Client($args); // etc..
Handling Exceptions
When the circuit breaker is in an open state, it throws the ResilientClient\CircuitBreaker\Exceptions\CircuitBreakerException exception class. This exception serves as a signal that the circuit is currently open and requests to the service are not allowed. You can catch this exception to implement custom handling logic in your application when the circuit is open.
Example usage:
use GuzzleHttp\Client; use GuzzleHttp\Handler\CurlHandler; use GuzzleHttp\HandlerStack; use ResilientClient\CircuitBreaker\Adapters\FileStorageAdapter; use ResilientClient\CircuitBreaker\CircuitBreaker; use ResilientClient\CircuitBreaker\Middleware\CircuitBreakerGuzzleMiddleware; $adapter = new FileStorageAdapter; $adapter->setPath(__DIR__ . '/storage/'); $circuitBreaker = new CircuitBreaker($adapter); $circuitBreaker->setFailureThreshold(3); $circuitBreaker->setResetTimeout(300); $stack = HandlerStack::create(new CurlHandler()); $middleware = new CircuitBreakerGuzzleMiddleware($circuitBreaker); $middleware->setAsFailureRequestCodes(301, 302); $stack->push($middleware); $args['handler'] = $stack; $client = new Client($args); // etc..
Tests
composer test
License
The Resilient Client package is open-source software licensed under the MIT License.
endisha/resilient-client 适用场景与选型建议
endisha/resilient-client 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 9 次下载、GitHub Stars 达 2, 最近一次更新时间为 2023 年 08 月 29 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「package」 「php」 「client」 「pattern」 「design」 「circuit」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 endisha/resilient-client 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 endisha/resilient-client 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 endisha/resilient-client 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Mock PSR-18 HTTP client
Asynchronous MQTT client built on React
Simple ASCII output of array data
Client for Google Directions API to add interpolated points to a route consisting of given coordinates.
Alfabank REST API integration
统计信息
- 总下载量: 9
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 21
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2023-08-29