
PHP微服务架构设计实践微服务架构将单体应用拆分成多个独立服务每个服务独立开发、部署和扩展。PHP在微服务架构中可以作为服务提供者通过HTTP或RPC与其他服务通信。今天说说PHP微服务的设计与实现。微服务的核心是服务拆分和服务间通信。服务拆分按业务领域划分每个服务有自己的数据库。php// 服务注册与发现class ServiceRegistry{private Redis $redis;private string $prefix service:;private int $ttl 30;public function __construct(Redis $redis){$this-redis $redis;}public function register(string $name, string $host, int $port): void{$serviceKey $this-prefix . $name;$instanceId $host:$port;$this-redis-hSet($serviceKey, $instanceId, json_encode([host $host,port $port,registered_at time(),]));$this-redis-expire($serviceKey, $this-ttl);echo 服务注册: {$name} {$host}:{$port}\n;}public function heartbeat(string $name, string $host, int $port): void{$serviceKey $this-prefix . $name;$instanceId $host:$port;$this-redis-expire($serviceKey, $this-ttl);}public function discover(string $name): ?array{$serviceKey $this-prefix . $name;$instances $this-redis-hGetAll($serviceKey);if (empty($instances)) return null;$services [];foreach ($instances as $id $data) {$services[] json_decode($data, true);}// 随机选择一个实例负载均衡return $services[array_rand($services)];}public function getAllInstances(string $name): array{$serviceKey $this-prefix . $name;$instances $this-redis-hGetAll($serviceKey);$result [];foreach ($instances as $id $data) {$result[] json_decode($data, true);}return $result;}public function deregister(string $name, string $host, int $port): void{$serviceKey $this-prefix . $name;$instanceId $host:$port;$this-redis-hDel($serviceKey, $instanceId);}}$redis new Redis();$redis-connect(127.0.0.1, 6379);$registry new ServiceRegistry($redis);$registry-register(user-service, 192.168.1.10, 9001);$registry-register(order-service, 192.168.1.11, 9002);$instance $registry-discover(user-service);echo 发现服务: . json_encode($instance) . \n;?服务间通信用HTTP客户端phpclass MicroserviceClient{private ServiceRegistry $registry;private array $cache [];public function __construct(ServiceRegistry $registry){$this-registry $registry;}public function call(string $service, string $method, string $path, array $data []): array{$instance $this-registry-discover($service);if ($instance null) {throw new RuntimeException(服务不可用: $service);}$url http://{$instance[host]}:{$instance[port]}{$path};$ch curl_init($url);$options [CURLOPT_RETURNTRANSFER true,CURLOPT_TIMEOUT 5,CURLOPT_HTTPHEADER [Content-Type: application/json,X-Request-Id: . uniqid(),X-Source-Service: api-gateway,],];switch (strtoupper($method)) {case POST:$options[CURLOPT_POST] true;$options[CURLOPT_POSTFIELDS] json_encode($data);break;case PUT:$options[CURLOPT_CUSTOMREQUEST] PUT;$options[CURLOPT_POSTFIELDS] json_encode($data);break;case DELETE:$options[CURLOPT_CUSTOMREQUEST] DELETE;break;}curl_setopt_array($ch, $options);$response curl_exec($ch);$httpCode curl_getinfo($ch, CURLINFO_HTTP_CODE);curl_close($ch);return [status $httpCode,body json_decode($response, true) ?? [],];}public function callWithRetry(string $service, string $method, string $path, array $data [], int $maxRetries 3): array{$lastException null;for ($i 0; $i $maxRetries; $i) {try {$result $this-call($service, $method, $path, $data);if ($result[status] 500) {return $result;}} catch (Exception $e) {$lastException $e;usleep(100000 * ($i 1));}}throw new RuntimeException(服务调用失败: $service, 0, $lastException);}public function callWithCircuitBreaker(string $service, string $method, string $path, array $data []): array{$state $this-getCircuitState($service);if ($state open) {throw new RuntimeException(断路器已打开: $service);}try {$result $this-call($service, $method, $path, $data);$this-recordSuccess($service);return $result;} catch (Exception $e) {$this-recordFailure($service);throw $e;}}private function getCircuitState(string $service): string{$key circuit:{$service};$failures apcu_fetch($key) ?: 0;return $failures 5 ? open : closed;}private function recordSuccess(string $service): void{apcu_store(circuit:{$service}, 0);}private function recordFailure(string $service): void{$key circuit:{$service};$failures apcu_fetch($key) ?: 0;apcu_store($key, $failures 1);}}?// 服务端中间件class MicroserviceMiddleware{public static function handle(): void{// 请求ID$requestId $_SERVER[HTTP_X_REQUEST_ID] ?? uniqid();header(X-Request-Id: . $requestId);// 请求耗时$start microtime(true);// 响应格式header(Content-Type: application/json; charsetutf-8);register_shutdown_function(function () use ($start, $requestId) {$duration (microtime(true) - $start) * 1000;$log json_encode([request_id $requestId,method $_SERVER[REQUEST_METHOD],uri $_SERVER[REQUEST_URI],status http_response_code(),duration_ms round($duration, 2),], JSON_UNESCAPED_UNICODE);file_put_contents(/var/log/microservice.log, $log . \n, FILE_APPEND);});}}MicroserviceMiddleware::handle();echo json_encode([status ok, service user-service]);?微服务架构带来了灵活性也增加了复杂性。服务发现、负载均衡、熔断、限流、分布式追踪这些都是需要考虑的问题。对于大多数团队来说从单体应用开始在确实需要的时候才拆分微服务是比较务实的方式。