微服务拆分在 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)