PHP服务降级与熔断机制实现

PHP服务降级与熔断机制实现 PHP服务降级与熔断机制实现在微服务架构中服务之间的依赖关系可能导致级联故障。熔断和降级是防止故障扩散的重要机制。今天说说PHP中服务降级和熔断的实现。熔断器有三种状态关闭、打开、半开。正常时熔断器关闭连续失败后熔断器打开请求快速失败。一段时间后进入半开状态允许部分请求通过测试服务是否恢复。phpclass CircuitBreaker{private string $name;private int $failureThreshold;private int $successThreshold;private int $timeout;private string $state closed;private int $failureCount 0;private int $successCount 0;private ?int $lastFailureTime null;private ?int $lastOpenTime null;public function __construct(string $name,int $failureThreshold 5,int $successThreshold 2,int $timeout 30) {$this-name $name;$this-failureThreshold $failureThreshold;$this-successThreshold $successThreshold;$this-timeout $timeout;}public function call(callable $operation, callable $fallback null): mixed{if ($this-isOpen()) {if ($this-shouldAttemptReset()) {$this-state half-open;echo 熔断器半开: {$this-name}\n;} else {echo 熔断器打开快速失败: {$this-name}\n;return $fallback ? $fallback() : null;}}try {$result $operation();$this-onSuccess();return $result;} catch (\Exception $e) {$this-onFailure();echo 调用失败 ({$this-failureCount}/{$this-failureThreshold}): {$e-getMessage()}\n;return $fallback ? $fallback() : null;}}public function isOpen(): bool{return $this-state open;}public function isHalfOpen(): bool{return $this-state half-open;}public function isClosed(): bool{return $this-state closed;}public function getState(): string{return $this-state;}public function getMetrics(): array{return [name $this-name,state $this-state,failure_count $this-failureCount,success_count $this-successCount,failure_threshold $this-failureThreshold,];}private function shouldAttemptReset(): bool{if ($this-lastOpenTime null) return true;return time() - $this-lastOpenTime $this-timeout;}private function onSuccess(): void{if ($this-state half-open) {$this-successCount;if ($this-successCount $this-successThreshold) {$this-reset();echo 熔断器关闭: {$this-name}\n;}} else {$this-failureCount 0;}}private function onFailure(): void{$this-failureCount;$this-lastFailureTime time();if ($this-state half-open || $this-failureCount $this-failureThreshold) {$this-state open;$this-lastOpenTime time();echo 熔断器打开: {$this-name} ({$this-timeout}秒后尝试恢复)\n;}}private function reset(): void{$this-state closed;$this-failureCount 0;$this-successCount 0;$this-lastFailureTime null;$this-lastOpenTime null;}}class ServiceWithFallback{private CircuitBreaker $breaker;private int $requestCount 0;public function __construct(){$this-breaker new CircuitBreaker(payment-service, 3, 2, 10);}public function processPayment(float $amount): string{$this-requestCount;return $this-breaker-call(// 主要操作function () use ($amount) {// 模拟不稳定服务if (rand(0, 2) 0) {throw new \RuntimeException(支付服务超时);}return 支付成功: {$amount}元;},// 降级操作function () use ($amount) {return 支付降级: {$amount}元已记录稍后处理;});}public function getMetrics(): array{return array_merge([total_requests $this-requestCount],$this-breaker-getMetrics());}}$service new ServiceWithFallback();for ($i 0; $i 10; $i) {$result $service-processPayment(100.00);echo 结果: {$result}\n;sleep(1);}echo \n最终状态:\n;print_r($service-getMetrics());?服务降级策略的实现phpclass DegradationManager{private array $degradations [];private Redis $redis;public function __construct(Redis $redis){$this-redis $redis;}public function enableDegradation(string $service, callable $fallback): void{$key degradation:{$service};$this-redis-setex($key, 3600, 1);$this-degradations[$service] $fallback;}public function disableDegradation(string $service): void{$this-redis-del(degradation:{$service});unset($this-degradations[$service]);}public function isDegraded(string $service): bool{return (bool)$this-redis-get(degradation:{$service});}public function execute(string $service, callable $primary): mixed{if ($this-isDegraded($service) isset($this-degradations[$service])) {return ($this-degradations[$service])();}return $primary();}}?熔断和降级是构建弹性系统的关键。熔断器防止故障扩散降级策略保证核心功能的可用性。在分布式系统中没有熔断机制的服务容易被故障拖垮。合理设置熔断阈值和超时时间配合监控告警系统可以构建高可用的微服务架构。