微服务拆分在 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[hostenv(NACOS_HOST,127.0.0.1),portenv(NACOS_PORT,8848),namespace_idenv(NACOS_NAMESPACE,),],],enable[discoverytrue,registertrue,],];---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{$orderOrder::create([user_id$userId,totalcollect($items)-sum(price),statuspending,]);return$order-toArray();}publicfunctionfind(int$orderId): array{returnOrder::findOrFail($orderId)-toArray();}}config/autoload/server.php 添加 jsonrpc server[namejsonrpc,typeServer::SERVER_HTTP,host0.0.0.0,port9504,callbacks[Event::ON_REQUEST[Hyperf\JsonRpc\HttpServer::class,onRequest],],], ---4. 服务消费方API Gateway?php // config/autoload/services.php consumers 段return[consumers[[nameOrderService,service\Contract\Order\OrderServiceInterface::class,protocoljsonrpc-http,load_balancerrandom,registry[protocolnacos],],],];控制器直接注入?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[errorOrder service unavailable,retry_after10];}publicfunctionfind(int$orderId): array{return$this-client-find($orderId);}}---6. 链路追踪OpenTelemetry config/autoload/opentracing.php?phpreturn[defaultenv(TRACER_DRIVER,jaeger),tracer[jaeger[driver\Hyperf\Tracer\Adapter\JaegerTracerFactory::class,nameenv(APP_NAME),options[sampler[type\Jaeger\SAMPLER_TYPE_CONST,paramtrue],local_agent[reporting_hostenv(JAEGER_HOST,127.0.0.1),reporting_portenv(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[statuspaid];}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跨语言场景用 gRPChyperf/grpc-client