服务发现
服务发现用于在客户端解析服务的实际地址,并支持简单的客户端负载均衡。
1. 核心接口
ServiceResolverInterface
php
interface ServiceResolverInterface
{
public function resolve(ServiceLocatorInterface $serviceLocator): ?ServiceEndpoint;
}ServiceEndpoint
php
$endpoint = new ServiceEndpoint([
Endpoint::fromString('http://10.0.0.1:8080'),
Endpoint::fromString('http://10.0.0.2:8080'),
]);
$endpoint->getEndpoints();
$endpoint->getEndpoint('10.0.0.1:8080');
$endpoint->isEmpty();
$endpoint->remove($endpoint);2. ServiceDiscovery 中间件
php
use kuiper\rpc\client\middleware\ServiceDiscovery;
$middleware = new ServiceDiscovery(
serviceResolver: $resolver,
cache: $cache,
loadBalance: 'round_robin'
);参数:
| 参数 | 说明 |
|---|---|
serviceResolver | 服务地址解析器 |
cache | PSR-16 缓存,缓存 ServiceEndpoint |
loadBalance | round_robin(默认)或 random |
行为:
- 以
(string) ServiceLocator为 key 查询缓存 - 缓存未命中时调用
ServiceResolverInterface::resolve() - 解析结果为空时抛
ResolveAddressFailedException - 按负载均衡策略选择一个
Endpoint - 写入请求:
$request->withEndpoint($endpoint)
3. 内置 Resolver
StaticServiceResolver(静态地址表)
直接从配置读取「服务 → 地址列表」映射,零外部依赖,适合地址固定的场景 (内网固定地址、单实例部署、本地开发):
php
use kuiper\rpc\servicediscovery\StaticServiceResolver;
$resolver = new StaticServiceResolver([
// 完整键:namespace:name:version
'demo:demo.DemoService:1.0' => ['http://10.0.0.1:8080', 'http://10.0.0.2:8080'],
// 也支持只写服务名
'demo.OtherService' => ['http://10.0.0.3:8080'],
]);匹配顺序:先按完整 locator 字符串精确匹配,再按服务名兜底。
DnsServiceResolver(DNS 解析)
把服务定位器按模板生成主机名,通过 DNS(A 记录或 SRV 记录)解析出多个端点, 适合 K8s headless service 等场景:
php
use kuiper\rpc\servicediscovery\DnsServiceResolver;
// create() 优先使用 netdns2 扩展,未安装时自动回退到原生实现
$resolver = DnsServiceResolver::create(
hostnameTemplate: '{namespace}-{server}', // 占位符:{namespace}/{name}/{version}/{app}/{server}
protocol: 'tcp',
queryPrefix: '', // SRV 记录一般用 _service._proto.
);{app} 是服务名按 . 拆分后的第一段,{server} 是最后一段 (如 demo.UserService → app=demo、server=UserService)。
自定义 Resolver
php
use kuiper\rpc\message\ServiceLocatorInterface;
use kuiper\rpc\servicediscovery\ServiceEndpoint;
use kuiper\rpc\servicediscovery\ServiceResolverInterface;
use kuiper\rpc\transporter\Endpoint;
class ConfigServiceResolver implements ServiceResolverInterface
{
public function __construct(private readonly array $services)
{
}
public function resolve(ServiceLocatorInterface $locator): ?ServiceEndpoint
{
$addresses = $this->services[$locator->getName()] ?? [];
return new ServiceEndpoint(array_map(
static fn (string $address): Endpoint => Endpoint::fromString($address),
$addresses
));
}
}4. 接入客户端
通过配置启用(推荐)
RpcClientConfiguration 支持 application.rpc.default.service_discovery 配置, 开启后会自动把 ServiceDiscovery 中间件挂在中间件链首 (它必须早于 codec 编码执行,才能用解析出的地址替换请求地址):
php
'application' => [
'rpc' => [
'default' => [
'service_discovery' => [
'enabled' => true, // 或环境变量 RPC_SERVICE_DISCOVERY_ENABLED=true
'type' => 'static', // static(静态地址表)或 dns(DNS 解析)
'load_balance' => 'round_robin', // 或 random
'services' => [ // 静态地址表(type=static)
'demo:demo.DemoService:1.0' => ['http://10.0.0.1:8080'],
],
// type=dns 时的可选项:
// 'hostname_template' => '{namespace}-{server}',
// 'protocol' => 'tcp',
// 'query_prefix' => '',
],
],
],
],手动构造
也可以自己组装(例如需要自定义 resolver 时):
php
use kuiper\rpc\client\DefaultRpcRequestHandler;
use kuiper\rpc\client\ProxyGenerator;
use kuiper\rpc\client\RpcExecutorFactory;
use kuiper\rpc\client\middleware\ServiceDiscovery;
use kuiper\rpc\codec\CodecRegistry;
use kuiper\rpc\codec\HttpJsonRpcCodec;
use kuiper\rpc\transporter\GuzzleHttpTransporter;
$handler = new DefaultRpcRequestHandler(
new GuzzleHttpTransporter(new \GuzzleHttp\Client()),
new CodecRegistry([new HttpJsonRpcCodec()])
);
$executorFactory = new RpcExecutorFactory($handler, [
new ServiceDiscovery($resolver, $cache),
]);
$generated = (new ProxyGenerator($executorFactory))
->generate(DemoService::class);
$generated->eval();
$service = new ($generated->getClassName())($executorFactory);
HttpJsonRpcCodec::encodeRequest()使用RpcRequest::getEndpoint()生成 URI, 因此ServiceDiscovery必须在 codec 编码之前执行(即放在中间件链中)。
5. 缓存
ServiceDiscovery 需要 PSR-16 CacheInterface。可以使用:
kuiper\cache\SimpleCache(基于 PSR-6 CacheItemPool)- 任意 PSR-16 实现
示例:
php
$cache = new \kuiper\cache\SimpleCache($cacheItemPool);缓存 key 是 ServiceLocator 的字符串形式:
text
namespace:name:version6. 负载均衡
round_robin
每个 service locator 维护独立计数:
php
$index = $this->roundRobinIndexes[$locatorKey]++;
return $endpoints[$index % count($endpoints)];random
php
return $endpoints[array_rand($endpoints)];7. 错误处理
无法解析服务或地址列表为空时:
php
throw new ResolveAddressFailedException($request, "Cannot resolve service $key", 0, $e);调用方可以捕获 ResolveAddressFailedException 做降级或重试。
8. 当前限制
- 内置的静态地址表在进程启动时固定,运行期不感知服务实例变化; 需要动态地址时实现自定义
ServiceResolverInterface或接入注册中心。 ServiceDiscovery的缓存没有内置 TTL 管理,依赖传入的 PSR-16 缓存实现。- 没有内置的健康检查/地址摘除机制;可在自定义
ServiceResolverInterface中实现。