概念
gRPC:基于RPC的一种远程调用协议(php平台只支持gRPC客户端调用,不支持gRPC服务端实现)
Protobuf:语言无关的高效数据交换协议,用于支持gRPC在不同语言间序列化和反序列化数据,具体的数据交换约定由.proto文件定义
安装
sudo yum -y install unzip libtool
git clone -b $(curl -L https://grpc.io/release) https://github.com/grpc/grpc
cd grpc
git pull --recurse-submodules && git submodule update --init --recursive
make & sudo make install
# 编译导出文件中,常用的有:
# grpc/bins/opt/protobuf/protoc:proto文件编译器
# grpc/bins/opt下生成了各类语言的gRPC编译插件,用于配合protoc编译器生成客户端基类
sudo pecl install grpc
sudo pecl install protobuf
composer require grpc/grpc --profile --prefer-dist --optimize-autoloader
composer require google/protobuf --profile --prefer-dist --optimize-autoloader
使用
proto文件示例
syntax = "proto3";
package grpc.services.list; #默认包路径
//针对不同语言自定义包路径
option php_package = "com.service.grpc";
//服务
service ListService {
//方法定义
rpc FetchListByUid(ListRequest) returns (ListResponse) {};
}
//请求
message ListRequest {
string uid = 1;
}
//响应
message ListResponse {
string result = 1;
}
编译proto文件,导出客户端类
protoc --php_out=src/generated_code/grpc
--grpc_out=src/generated_code/grpc
--plugin=protoc-gen-grpc=bins/opt/grpc_php_plugin
path/your.proto
调用示例
$request = (new ListRequest())->setUid($id);
$client = new ListServiceClient("gRPC主机:端口", [
'credentials' => ChannelCredentials::createInsecure(),
'timeout' => 1000000,
]);
list($reply, $status) = $client->FetchListByUid($request)->wait();
$reply->getXxx();
$client->close();