Skip to content

RPC 客户端 ​

Kuiper RPC 客户端使用「接口 + #[RpcClient] + 容器代理」的方式调用远程服务。

1. 定义接口 ​

php
<?php
declare(strict_types=1);

namespace App\rpc;

use kuiper\rpc\attribute\RpcClient;

#[RpcClient(ns: 'demo', service: 'demo.DemoService', version: '1.0')]
interface DemoService
{
    public function hello(string $name): string;

    public function add(int $a, int $b): int;

    /**
     * @return Order[]
     */
    public function listOrders(string $userId): array;
}

#[RpcClient] 参数:

参数默认值说明
service''服务名,建议显式设置
version''服务版本
ns''服务命名空间
serialization'jsonrpc'报文格式:tars 为 TARS 报文(v0.8 兼容),jsonrpc 为严格 JSON-RPC 2.0。attribute 上填 tars 时优先生效,否则取 application.rpc 里的配置(默认 tars)
namenull组件别名(DI 用)
protocol''v0.8 兼容项,保留但不再使用
endpoint''v0.8 兼容项:完整服务地址(http://host:port/path),作为服务地址的默认值,优先级低于环境变量

位置传参的顺序是 (service, version, ns, ...),与 v0.8 一致;推荐用具名传参。

该接口必须放在 component_scan 扫描的命名空间下,RpcClientConfiguration 会为它生成代理定义。

用 tars-generator 生成接口 ​

服务提供方通常会把 .tars 定义分发给调用方,用 wenbinye/tars-gen 直接生成上面的接口与 DTO:

bash
# 单文件:--client 生成 #[RpcClient] 接口(不加则是服务端的 #[RpcService] 接口);
# --strict-type / --use-php-enum 是项目模式的默认值,命令行方式要显式传
./vendor/bin/tars-gen --client --protocol=jsonrpc --strict-type --use-php-enum \
    --namespace='App\rpc' --psr4-namespace='App' -o src path/to/Hello.tars
# → src/rpc/<module>/HelloServant.php,namespace App\rpc\<module>

# 项目模式:tars/config.json + tars/jsonrpc/*.tars,在项目根目录执行
./vendor/bin/tars-gen
json
{
    "servant": { "protocol": "jsonrpc" },
    "jsonrpc": {
        "servants": { "Ip": "IpObj.winwin-ip" }
    }
}

生成结果(src/integration/ip/IpServant.php):

php
namespace App\integration\ip;

#[RpcClient(service: 'IpObj', ns: 'winwin-ip')]
interface IpServant
{
    public function query(string $ip): IpInfo;
}
  • servants 的值是 obj名.服务名:obj 名成为 service,服务名成为 ns。ns 不参与报文, 只用来匹配服务地址,winwin\support 会把它当作服务的主机名(host = ns + JSONRPC_DEFAULT_SUB_DOMAIN)
  • servant 段把服务端自己的 .tars 生成为实现类要实现的接口;jsonrpc 段把调用方的 .tars 生成为客户端接口
  • 同一个 .tars 文件只归一个段使用(生成结果按文件路径缓存),服务端和调用方各放一份副本
  • 生成后通常再执行 php-cs-fixer(各服务的 composer gen 脚本都是这么做的)
  • 生成的接口不带 serialization:报文格式由 application.rpc 的 serialization、 services 匹配项或环境变量 RPC_{NS}_{SERVICE}__SERIALIZATION 决定,与服务端的 RPC_SERVER_CODEC 保持一致
  • 修改 tars/config.json 后要删除 .tars-gen.cache,否则 .tars 文件没变时不会重新生成
  • 必须显式传 --protocol=jsonrpc:默认的 tars 协议模板生成的是 #[TarsClient] / #[TarsParameter], kuiper v0.9 没有 kuiper\tars 命名空间,生成的代码无法使用
  • out 参数(TARS 多输出)生成为 PHP 引用参数 ?string &$message,客户端代理会自动回填
  • vector&lt;byte&gt; 生成为 kuiper\serializer\BinaryString 字段,JSON 中以 base64 传输

2. 容器配置 ​

php
<?php
// src/container.php
return [
    'component_scan' => [
        'App\\rpc',
    ],
    'configuration' => [
        \kuiper\serializer\SerializerConfiguration::class,
        \kuiper\reflection\ReflectionConfiguration::class,
        \kuiper\rpc\RpcClientConfiguration::class,
    ],
];

RpcClientConfiguration 已经依赖 SerializerConfiguration 和 ReflectionConfiguration,显式列出只是为了说明依赖关系。

生产环境接入前请先读客户端最佳实践:配置层次与优先级、 超时设置(默认不设超时,必须显式配置)、中间件顺序都有明确建议。

3. 配置服务地址 ​

php
<?php
// src/config.php
return [
    'application' => [
        'rpc' => [
            'default' => [
                'protocol' => 'http',
                'serialization' => 'tars',
                'host' => '127.0.0.1',
                'port' => 8080,
                'path' => '/rpc',
                'tls' => false,
            ],
            'services' => [
                [
                    'ns' => 'demo',
                    'service' => 'demo.DemoService',
                    'version' => '1.0',
                    'host' => '10.0.0.10',
                    'port' => 8080,
                    'path' => '/rpc',
                ],
            ],
        ],
    ],
];

配置优先级:

text
环境变量 > attribute 上的 endpoint > application.rpc.services 匹配项 > application.rpc.default

都没配 host 时以客户端的服务命名空间(ns)作为主机名(零配置寻址,与 v0.8 一致):#[RpcClient(ns: 'winwin-corp')] 的客户端在没有任何地址配置时,请求发往 http://winwin-corp:8000/rpc——ns 同时是 k8s headless Service 的名字,由集群 DNS 解析到服务 pod。端口默认 8000。详见零配置寻址。

环境变量有两种前缀,新的优先:

text
RPC_{NS}_{SERVICE}__{HOST|PORT|PATH|SERIALIZATION}      # v0.9 约定
JSONRPC_CLIENT_{接口全类名}__{HOST|PORT|...|ENDPOINT}  # v0.8 约定(ENDPOINT 为完整 URL)

services 匹配规则:

  • ns 和 service 必须与 #[RpcClient] 一致
  • version 非空时精确匹配
  • version 为空时作为通配,但精确版本优先

最终 endpoint:

text
{scheme}://{host}:{port}{path}

scheme 由 tls=true 或端口 443 决定。

解析出来的 endpoint 会附加到每一个 RPC 请求上,请求 URL 由它生成(scheme、host、port、path 全部生效)。 若启用了服务发现(ServiceDiscovery 中间件),服务发现给出的 host:port 会覆盖 host/port, 请求路径仍沿用这里配置的 path。

环境变量覆盖 ​

格式:

text
RPC_{NS}_{SERVICE}__{KEY}

其中 ns、service 转大写,. 和 \ 替换为 _。

例如:

bash
# ns=demo, service=DemoService
export RPC_DEMO_DEMOSERVICE__HOST=10.0.0.10
export RPC_DEMO_DEMOSERVICE__PORT=8080

# ns=demo, service=demo.DemoService
export RPC_DEMO_DEMO_DEMOSERVICE__HOST=10.0.0.10

支持的 KEY:protocol、host、port、path、tls、serialization 等。

ns / service 中的 .、\、- 都替换为 _,所以 #[RpcClient(service: 'EventBusObj', ns: 'winwin-event-bus')] 对应的前缀是 RPC_WINWIN_EVENT_BUS_EVENTBUSOBJ__。

环境变量同时从 $_ENV 与进程环境(getenv())读取,因此 variables_order 不含 E 时也生效。

serialization 决定报文格式:

取值报文格式
tars(默认)TARS 报文:位置参数、裸 result、业务错误码,支持 out 参数
jsonrpc严格 JSON-RPC 2.0:params 按参数名、result 为 [返回值]、标准错误码

4. 注入代理 ​

php
class OrderApplication
{
    public function __construct(
        private readonly DemoService $demoService,
    ) {
    }

    public function run(): string
    {
        return $this->demoService->hello('Kuiper');
    }
}

容器中 DemoService::class 实际是动态生成的代理类:

text
\kuiper\rpc\client\generated\DemoServiceProxy

代理由 ProxyGenerator 使用 laminas/laminas-code 生成,并通过 eval() 加载。目标必须是 interface。

代理方法原样保留接口签名:参数默认值(?string $x = null)、variadic (string ...$parts)与联合返回类型(: int|string)都会被完整生成。 (v0.9.3 生成这类签名时会丢失细节、在 eval() 阶段直接 Fatal, 见 M39。)代理类名掺入接口全限定名的摘要, 不同命名空间下的同名接口不会互相覆盖。

5. 请求执行流程 ​

text
代理方法
  → RpcExecutorFactory::createExecutor()
  → RpcRequestFactory::createRequest()
  → RpcExecutor::execute()
  → MiddlewareStack
  → DefaultRpcRequestHandler
  → Codec.encodeRequest()
  → Transporter.send()
  → Codec.decodeResponse()
  → 返回值反序列化

6. DTO 序列化 ​

请求参数 ​

标量、null、数组直接透传;对象参数由 Serializer::normalize() 转成数组:

php
public function createOrder(CreateOrder $order): int;

发送的 JSON-RPC params 中 order 会变成普通数组。

返回值 ​

RpcExecutor 根据接口方法的返回类型和 PHPDoc 反序列化:

php
public function findOrder(string $id): Order;          // DTO
/** @return Order[] */
public function listOrders(string $userId): array;      // DTO 数组
public function count(): int;                           // 标量
public function delete(string $id): void;               // void → null

支持:

  • 标量、null
  • 类类型(Serializer::denormalize)
  • 数组元素类型(Order[]、int[])
  • 可空类型、联合类型(按顺序尝试)

DTO 属性类型校验是严格的:null 落到非空类型属性会抛 TypeError

Serializer::denormalize 按属性声明类型赋值:数据里的 null 落到声明为 string 等非空类型的属性时,直接抛 PHP TypeError (Cannot assign null to property ... of type string)——请求参数与服务端 读 DTO 两个方向都是这个行为。

典型场景:存量数据里有 NULL 字段(如 payload 列历史上放过 NULL), DTO 字段声明为 string 时,命中旧行即抛 TypeError。处理方式二选一:

  • 先清洗存量数据(NULL → 空串 / 默认值);
  • 或把 DTO 字段放宽为 ?string,业务代码自行处理 null。

7. 错误处理 ​

异常场景
kuiper\rpc\exception\RpcResponseExceptionJSON-RPC 返回 error(业务错误码用 getRpcCode() 取)
kuiper\rpc\exception\ConnectionException连接失败 / 请求超时(Guzzle 的超时映射为连接异常)
kuiper\rpc\exception\RequestExceptionHTTP 请求失败 / 非预期响应

代码库中不存在会被抛出的 TimedOutException;超时统一表现为 ConnectionException。

业务错误码:从报文解码出来的响应同时把业务码写入 \Exception::getCode(),因此解码路径下 getCode() === getRpcCode();只有手动构造 RpcResponseException 时 getCode() 默认才是 0。

8. 自定义 Transporter / Codec ​

RpcClientConfiguration 内部使用:

php
$transporter = new GuzzleHttpTransporter($httpClient);
$handler = new DefaultRpcRequestHandler(
    $transporter,
    new CodecRegistry([new HttpJsonRpcCodec()])
);
$executorFactory = new RpcExecutorFactory($handler, $middlewares, null, $serializer);

需要 TCP 或自定义传输时,可以手动构造 RpcExecutorFactory / ProxyGenerator:

php
$transporter = new SocketTcpTransporter(Endpoint::fromAddress('127.0.0.1:9000'));
$handler = new DefaultRpcRequestHandler(
    $transporter,
    new CodecRegistry([new TcpJsonRpcCodec()])
);
$executorFactory = new RpcExecutorFactory($handler, $middlewares);
$proxy = (new ProxyGenerator($executorFactory))
    ->generate(DemoService::class);
$proxy->eval();
$service = new ($proxy->getClassName())($executorFactory);

9. 中间件 ​

客户端中间件通过配置 middlewares 挂载(类名列表,数组第一个最外层), RpcClientConfiguration::resolveMiddlewares() 会从容器解析它们。 启用 service_discovery.enabled 时,服务发现中间件会被自动加在最前面, 无需手动注入:

php
// container.php / envOptions 中的客户端配置
return [
    'middlewares' => [
        kuiper\rpc\client\middleware\AccessLog::class,
        kuiper\resilience\middleware\CircuitBreaker::class,  // 需启用弹性组件配置
    ],
    'service_discovery' => ['enabled' => true],
];

详见 中间件。

10. 当前限制 ​

  • RpcClientConfiguration 只支持 http 协议(https 由 tls 配置控制,见 configuration.md)。
  • 代理类通过 eval() 加载,生产环境建议缓存生成的代理类。

基于 MIT 许可发布