php 实现熔断
熔断机制简介
熔断是一种系统保护机制,当服务调用失败率达到阈值时,自动停止请求并快速失败,避免雪崩效应。常见实现方式包括计数器、滑动窗口等。

基于计数器的熔断实现
通过记录失败请求次数,当达到阈值时触发熔断:

class CircuitBreaker {
private $failureThreshold = 3;
private $failureCount = 0;
private $state = 'CLOSED';
public function callService(callable $service) {
if ($this->state === 'OPEN') {
throw new Exception("Service unavailable (Circuit Breaker Open)");
}
try {
$result = $service();
$this->reset();
return $result;
} catch (Exception $e) {
$this->failureCount++;
if ($this->failureCount >= $this->failureThreshold) {
$this->state = 'OPEN';
// 可添加定时器自动恢复
}
throw $e;
}
}
private function reset() {
$this->failureCount = 0;
$this->state = 'CLOSED';
}
}
基于时间窗口的熔断改进
记录最近N秒内的失败率,更精准判断熔断状态:
class TimeWindowBreaker {
private $windowSize = 10; // 秒
private $failureRateThreshold = 0.5;
private $failures = [];
private $state = 'CLOSED';
public function callService(callable $service) {
$this->cleanOldFailures();
if ($this->state === 'OPEN') {
throw new Exception("Service unavailable");
}
try {
$result = $service();
return $result;
} catch (Exception $e) {
$this->failures[] = time();
$this->evaluateState();
throw $e;
}
}
private function cleanOldFailures() {
$currentTime = time();
$this->failures = array_filter(
$this->failures,
fn($t) => $currentTime - $t <= $this->windowSize
);
}
private function evaluateState() {
$totalCalls = count($this->failures) + 1; // +1 for current call
$failureRate = count($this->failures) / $totalCalls;
if ($failureRate >= $this->failureRateThreshold) {
$this->state = 'OPEN';
// 可设置延迟恢复逻辑
}
}
}
熔断状态恢复策略
- 自动恢复:通过定时器定期尝试重置状态
- 半开状态:允许部分请求通过测试稳定性
// 半开状态示例代码片段
if ($this->state === 'OPEN' && time() - $this->lastFailure > $this->cooldownPeriod) {
$this->state = 'HALF_OPEN';
try {
$testResult = $service();
$this->reset();
} catch (Exception $e) {
$this->lastFailure = time();
}
}
集成建议
- 结合Guzzle等HTTP客户端实现远程服务熔断
- 使用Redis共享熔断状态(分布式场景)
- 监控系统记录熔断事件以便分析
关键参数需根据实际业务调整:
- 失败阈值(如5次/10秒)
- 冷却时间(如30秒自动恢复)
- 采样窗口大小(如60秒滚动统计)






