Hyperf 官方内置 hyperf/circuit-breaker基于注解驱动零配置开箱即用。 --- 安装composerrequire hyperf/circuit-breaker ---1. 基础熔断注解方式?php namespace App\Service;use Hyperf\CircuitBreaker\Annotation\CircuitBreaker;class PaymentService{#[CircuitBreaker(fallback:[self::class,payFallback], exceptions:[\Throwable::class], attemptThreshold:3, // 连续失败3次开启熔断 recoveryTimeout:10, //10秒后尝试半开)]publicfunctionpay(int$orderId, float$amount): array{// 调用第三方支付return$this-httpClient-post(/pay, compact(orderId,amount));}publicfunctionpayFallback(int$orderId, float$amount): array{return[statuspending,messagePayment service unavailable];}}---2. 多服务熔断?php namespace App\Service;use Hyperf\CircuitBreaker\Annotation\CircuitBreaker;class ExternalService{// 库存服务 - 快速失败#[CircuitBreaker(fallback:[self::class,inventoryFallback], attemptThreshold:5, recoveryTimeout:30,)]publicfunctioncheckInventory(int$productId): array{return$this-inventoryClient-check($productId);}// 推荐服务 - 降级返回空#[CircuitBreaker(fallback:[self::class,recommendFallback], attemptThreshold:3, recoveryTimeout:60,)]publicfunctiongetRecommendations(int$userId): array{return$this-recommendClient-get($userId);}publicfunctioninventoryFallback(int$productId): array{return[availablefalse,fallbacktrue];}publicfunctionrecommendFallback(int$userId): array{return[];// 推荐服务降级返回空列表}}---3. 手动控制熔断状态?php namespace App\Service;use Hyperf\CircuitBreaker\CircuitBreakerFactory;use Hyperf\CircuitBreaker\State;class CircuitBreakerManager{publicfunction__construct(private CircuitBreakerFactory$factory){}publicfunctionstatus(string$service): array{$breaker$this-factory-get($service);return[service$service,statematch(true){$breaker-isOpen()open, // 熔断中$breaker-isHalfOpen()half-open,// 探测中 defaultclosed, // 正常},failures$breaker-getFailCounter(),];}// 手动重置运维用 publicfunctionreset(string$service): void{$this-factory-get($service)-close();}}---4. 熔断状态监控接口?php namespace App\Controller;use Hyperf\HttpServer\Annotation\Controller;use Hyperf\HttpServer\Annotation\GetMapping;use Hyperf\HttpServer\Annotation\PostMapping;#[Controller(prefix: /api/circuit-breaker)]class CircuitBreakerController{publicfunction__construct(private CircuitBreakerManager$manager){}#[GetMapping(path: {service}/status)]publicfunctionstatus(string$service): array{return$this-manager-status($service);}#[PostMapping(path: {service}/reset)]publicfunctionreset(string$service): array{$this-manager-reset($service);return[resettrue];}}---5. 结合 RPC 客户端?php namespace App\JsonRpc;use Contract\Order\OrderServiceInterface;use Hyperf\CircuitBreaker\Annotation\CircuitBreaker;class OrderServiceConsumer implements OrderServiceInterface{publicfunction__construct(private OrderServiceInterface$client){}#[CircuitBreaker(fallback:[self::class,fallback], attemptThreshold:3, recoveryTimeout:10,)]publicfunctioncreate(int$userId, array$items): array{return$this-client-create($userId,$items);}#[CircuitBreaker(fallback:[self::class,fallback], attemptThreshold:3, recoveryTimeout:10,)]publicfunctionfind(int$orderId): array{return$this-client-find($orderId);}publicfunctionfallback(mixed...$args): array{return[errorOrder service unavailable,retry_after10];}}--- 熔断状态机 正常请求 ↓[CLOSED]──连续失败 N 次──→[OPEN]──等待 T 秒──→[HALF-OPEN]↑ │ └──────────────── 探测成功 ─────────────────────────┘ │ 探测失败 →[OPEN]--- 核心要点 - attemptThreshold:3 recoveryTimeout:10是生产推荐起点 - fallback 方法签名必须与原方法一致 - 推荐/非核心服务降级返回空核心服务返回 pending 状态排队重试 - 手动 reset 接口给运维用服务恢复后快速闭合熔断器