ThinkSSL🔒 一键申购 5分钟快速签发 30天无理由退款 购买更放心 广告
## 服务注册 在前面的章节我们分析过 Go Micro 的实现原理,服务注册在微服务中的作用主要是实现动态的负载均衡,现在流行的服务注册中间件有 Consul、Etcd 等,其中 Etcd 是 k8s 的核心组件,社区非常活跃,使用非常简单且 Watch/KeepAlive 功能更加友好,因此 Mix 选择 Etcd 作为与 Go Micro 互通,后续再推出 Consul 的支持。 ## Mix Micro Etcd >[info] 需先安装 Etcd V3 使用 [composer](https://www.phpcomposer.com/) 安装: ``` composer require mix/micro-etcd ``` ## 依赖注入配置 - [manifest/beans/etcd.php](https://github.com/mix-php/mix-micro-skeleton/blob/master/manifest/beans/etcd.php) ## 服务注册 - ServiceFactory::class 提供了从 Mix Http Server / Route 中提取服务信息的功能,提取后 register 到注册中心即可。 ~~~ $registry = new \Mix\Micro\Etcd\Registry('http://127.0.0.1:2379/v3', $user, $password, $timeout); $serviceFactory = new ServiceFactory(); $services = $serviceFactory->createServiceFromAPI( $server, $route, 'php.micro.api' ); $registry->register(...$services); ~~~ - 查看 API 注册实例: [StartCommand.php#L103](https://github.com/mix-php/mix-micro-skeleton/blob/master/app/Api/Commands/StartCommand.php#L103) - 查看 gRPC 注册实例: [StartCommand.php#L95](https://github.com/mix-php/mix-micro-skeleton/blob/master/app/Grpc/Commands/StartCommand.php#L95) ## 服务获取 Mix 的 gRPC、JSON-RPC 客户端拨号器中只需传入上面的注册中心,就自动完成对应微服务的获取: - 服务中心的依赖配置:[manifest/beans/etcd.php#L5](https://github.com/mix-php/mix-micro-skeleton/blob/master/manifest/beans/etcd.php#L5) - 拨号器的依赖配置:[manifest/beans/grpc.php#L11](https://github.com/mix-php/mix-micro-skeleton/blob/master/manifest/beans/grpc.php#L11) - 通过拨号器调用微服务:[SayController.php#L54](https://github.com/mix-php/mix-micro-skeleton/blob/master/app/Api/Controllers/Greeter/SayController.php#L54)