news 2026/4/17 14:33:23

Hyperf方案 服务熔断器(Circuit Breaker)

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Hyperf方案 服务熔断器(Circuit Breaker)
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['status'=>'pending','message'=>'Payment 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['available'=>false,'fallback'=>true];}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,'state'=>match(true){$breaker->isOpen()=>'open', // 熔断中$breaker->isHalfOpen()=>'half-open',// 探测中 default=>'closed', // 正常},'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['reset'=>true];}}---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['error'=>'Order service unavailable','retry_after'=>10];}}--- 熔断状态机 正常请求 ↓[CLOSED]──连续失败 N 次──→[OPEN]──等待 T 秒──→[HALF-OPEN]↑ │ └──────────────── 探测成功 ─────────────────────────┘ │ 探测失败 →[OPEN]--- 核心要点: - attemptThreshold:3+ recoveryTimeout:10是生产推荐起点 - fallback 方法签名必须与原方法一致 - 推荐/非核心服务降级返回空,核心服务返回 pending 状态排队重试 - 手动 reset 接口给运维用,服务恢复后快速闭合熔断器
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/17 14:31:31

2026届学术党必备的六大降重复率方案横评

Ai论文网站排名&#xff08;开题报告、文献综述、降aigc率、降重综合对比&#xff09; TOP1. 千笔AI TOP2. aipasspaper TOP3. 清北论文 TOP4. 豆包 TOP5. kimi TOP6. deepseek 在学术研究范畴之内&#xff0c;免费的 AI 论文工具正逐渐地改变传统的写作方式&#xff0c;…

作者头像 李华
网站建设 2026/4/17 14:31:15

7-Zip完整指南:免费开源压缩软件的终极使用教程

7-Zip完整指南&#xff1a;免费开源压缩软件的终极使用教程 【免费下载链接】7z 7-Zip Official Chinese Simplified Repository (Homepage and 7z Extra package) 项目地址: https://gitcode.com/gh_mirrors/7z1/7z 你是否曾经因为文件太大无法通过邮件发送而烦恼&…

作者头像 李华
网站建设 2026/4/17 14:31:11

Python生物信息学终极指南:从入门到实战的完整教程

Python生物信息学终极指南&#xff1a;从入门到实战的完整教程 【免费下载链接】Bioinformatics-with-Python-Cookbook-Second-Edition 项目地址: https://gitcode.com/gh_mirrors/bi/Bioinformatics-with-Python-Cookbook-Second-Edition 《Bioinformatics-with-Pytho…

作者头像 李华
网站建设 2026/4/17 14:23:24

sCMOS相机在细胞生物学成像中的关键技术与系统应用

随着细胞生物学研究向高时间分辨率和单分子层面解析发展&#xff0c;成像系统逐步进入光子统计受限与动态过程主导的工作区间。在该条件下&#xff0c;探测器性能不再是系统组成部分之一&#xff0c;而成为决定实验结果的关键瓶颈。sCMOS&#xff08;scientific CMOS&#xff0…

作者头像 李华