当前位置: 首页 > news >正文

Hyperf方案 微服务拆分策略与实践

微服务拆分在 Hyperf 生态里有完整工具链: ┌───────────────┬──────────────────────────────────────────┐ │ 关注点 │ 库 │ ├───────────────┼──────────────────────────────────────────┤ │ 服务注册/发现 │ hyperf/service-governance + Consul/Nacos │ ├───────────────┼──────────────────────────────────────────┤ │ RPC 通信 │ hyperf/rpc-client + hyperf/json-rpc │ ├───────────────┼──────────────────────────────────────────┤ │ 服务熔断 │ hyperf/circuit-breaker │ ├───────────────┼──────────────────────────────────────────┤ │ 配置中心 │ hyperf/config-nacos │ ├───────────────┼──────────────────────────────────────────┤ │ 链路追踪 │ hyperf/tracer(OpenTelemetry)│ └───────────────┴──────────────────────────────────────────┘ --- 安装composerrequire hyperf/service-governance\hyperf/service-governance-nacos\hyperf/json-rpc\hyperf/rpc-client\hyperf/circuit-breaker\hyperf/tracer ---1. 服务注册(Nacos) config/autoload/services.php:<?phpreturn['consumers'=>[],'providers'=>[],'drivers'=>['nacos'=>['host'=>env('NACOS_HOST','127.0.0.1'),'port'=>env('NACOS_PORT',8848),'namespace_id'=>env('NACOS_NAMESPACE',''),],],'enable'=>['discovery'=>true,'register'=>true,],];---2. 定义 RPC 接口契约(共享包)<?php // 放在独立composer包中,各服务共享 namespace Contract\Order;interface OrderServiceInterface{publicfunctioncreate(int$userId, array$items): array;publicfunctionfind(int$orderId): array;}---3. 服务提供方(Order Service)<?php namespace App\JsonRpc;use Contract\Order\OrderServiceInterface;use Hyperf\RpcServer\Annotation\RpcService;#[RpcService(name:'OrderService', protocol:'jsonrpc-http', server:'jsonrpc', publishTo:'nacos',)]class OrderService implements OrderServiceInterface{publicfunctioncreate(int$userId, array$items): array{$order=Order::create(['user_id'=>$userId,'total'=>collect($items)->sum('price'),'status'=>'pending',]);return$order->toArray();}publicfunctionfind(int$orderId): array{returnOrder::findOrFail($orderId)->toArray();}}config/autoload/server.php 添加 jsonrpc server:['name'=>'jsonrpc','type'=>Server::SERVER_HTTP,'host'=>'0.0.0.0','port'=>9504,'callbacks'=>[Event::ON_REQUEST=>[Hyperf\JsonRpc\HttpServer::class,'onRequest'],],], ---4. 服务消费方(API Gateway)<?php // config/autoload/services.php consumers 段return['consumers'=>[['name'=>'OrderService','service'=>\Contract\Order\OrderServiceInterface::class,'protocol'=>'jsonrpc-http','load_balancer'=>'random','registry'=>['protocol'=>'nacos'],],],];控制器直接注入:<?php namespace App\Controller;use Contract\Order\OrderServiceInterface;use Hyperf\HttpServer\Annotation\Controller;use Hyperf\HttpServer\Annotation\PostMapping;#[Controller(prefix: '/api/orders')]class OrderController{publicfunction__construct(private OrderServiceInterface$orderService){}#[PostMapping(path: '')]publicfunctioncreate(): array{return$this->orderService->create(userId: auth()->id(), items:$this->request->input('items'),);}}---5. 熔断器<?php namespace App\JsonRpc;use Hyperf\CircuitBreaker\Annotation\CircuitBreaker;use Contract\Order\OrderServiceInterface;class OrderServiceConsumer implements OrderServiceInterface{publicfunction__construct(private OrderServiceInterface$client){}#[CircuitBreaker(fallback:[self::class,'fallback'], exceptions:[\Throwable::class], attemptThreshold:3, recoveryTimeout:10,)]publicfunctioncreate(int$userId, array$items): array{return$this->client->create($userId,$items);}publicfunctionfallback(int$userId, array$items): array{return['error'=>'Order service unavailable','retry_after'=>10];}publicfunctionfind(int$orderId): array{return$this->client->find($orderId);}}---6. 链路追踪(OpenTelemetry) config/autoload/opentracing.php:<?phpreturn['default'=>env('TRACER_DRIVER','jaeger'),'tracer'=>['jaeger'=>['driver'=>\Hyperf\Tracer\Adapter\JaegerTracerFactory::class,'name'=>env('APP_NAME'),'options'=>['sampler'=>['type'=>\Jaeger\SAMPLER_TYPE_CONST,'param'=>true],'local_agent'=>['reporting_host'=>env('JAEGER_HOST','127.0.0.1'),'reporting_port'=>env('JAEGER_PORT',5775),],],],],];手动埋点(可选,框架自动追踪 HTTP/RPC): use Hyperf\Tracer\SpanStarter;class PaymentService{use SpanStarter;publicfunctionpay(int$orderId, float$amount): array{$span=$this->startSpan('payment.process');$span->setTag('order.id',$orderId);try{// 支付逻辑return['status'=>'paid'];}finally{$span->finish();}}}--- 拆分原则速查 单体 微服务拆分边界 ───────────────────────────────────── UserModule → user-service(认证/权限独立)OrderModule → order-service(高频写,独立DB)PaymentModule → payment-service(强一致,TCC)NotifyModule → notify-service(异步,MQ驱动)SearchModule → search-service(Elasticsearch)核心要点: - 契约接口放独立composer包,provider/consumer 共享,避免重复定义 - 熔断 attemptThreshold:3+ recoveryTimeout: 10s 是生产推荐值 - 链路追踪框架层自动注入,无需每个方法手动埋点 - 服务间通信优先 JSON-RPC,跨语言场景用 gRPC(hyperf/grpc-client)
http://www.jsqmd.com/news/657241/

相关文章:

  • 【GitHub项目推荐--LingBot-Map:流式 3D 重建的几何上下文 Transformer】⭐⭐⭐⭐⭐
  • CSAPP 3e实验环境构建实战:从虚拟机到WSL的完整指南
  • 【研报317】2026年中国汽车行业趋势分析报告:新能源、智能网联、组合辅助驾驶重塑出行
  • 别再只盯着内存溢出了!从Unity崩溃日志中揪出AssetBundle.LoadAsset_Internal的真凶
  • 告别CAN总线焦虑:一文搞懂LIN协议在汽车车窗、车灯控制中的应用
  • 【零基础】在Ubuntu22.04上开始一个基于MotrixSim与MotrixLab的强化学习项目
  • Wand-Enhancer完全指南:免费解锁WeMod高级功能的终极解决方案
  • 算法训练营第四天|59.螺旋矩阵II
  • 亲测6款AI生成器,20分钟搞定6万字论文带数据分析 - 麟书学长
  • 2026年OpenClaw怎么搭建?3分钟腾讯云零技术安装OpenClaw及百炼Coding Plan步骤
  • 中启联信科技集团(数据要素全链路服务商|AI训练+数据资产入表双场景适配)
  • 鲸采云SRM深度测评:如何做到降低采购风险60%、采购成本35%?
  • 源雀SCRM商业版发布AI SKILLS:专属AI驱动的开发新范式
  • 保姆级教程:用Charades数据集复现行为识别模型(附PyTorch代码与避坑指南)
  • OpenClaw 2.6.2 Windows11 一键部署:一次安装,永久使用
  • 别再手动拖拽了!用Claude Desktop + Unity MCP插件,让AI帮你自动创建游戏场景(保姆级避坑指南)
  • 【语音信号处理】从可视化到特征:时域、频域、语谱图与MFCC的实战解析与代码实现
  • tapd-ai-cli——专为 AI Agent 打造的 TAPD 命令行工具
  • 手把手教你用Matlab实现KELM回归预测:从数据归一化到结果可视化全流程
  • 20260417
  • Unity C#脚本控制平滑移动——MoveTowards()方法的进阶应用与性能优化
  • 装修公司怎么选?2026设计施工一体公司推荐与避坑指南 - 品牌策略主理人
  • 保姆级教程:用C++在PX4飞控上实现无人机航线跟踪(Cross-track Error算法详解)
  • AI应用开发必看:Token、Skill、Agent、RAG四概念辨析,手把手教你打造可测知识问答Agent!
  • 如何5分钟完成DOL游戏汉化美化:终极整合包使用指南
  • Unity物理引擎实战:用GJK+EPA算法搞定2D碰撞后的物体分离(附完整C#源码)
  • WereYouLast
  • 差分式升压逆变器MATLAB仿真模型设计——实现110V/50Hz输出电压与THD<5%
  • OpenEMS开源能源管理系统:构建智能能源解决方案的完整指南
  • 海外短视频竞争升级跨境卖家如何提升内容吸引力