pecl install grpc
修改php.ini文件 添加 extension=grpc.so
通过php -m | grep grpc
查看grpc.so是否安装成功
以mac为例:参考链接 https://www.jianshu.com/p/f8b789280df4
protoc --version
查看是否安装成功
git clone -b v1.15.0 https://github.com/grpc/grpc
需要grpc-php-plugin来生成proto对应的php可执行文件。
cd grpc && git submodule update --init && make grpc_php_plugin
可与将 grpc_php_plugin 命令加入环境变量
syntax = "proto3";
package yunpian;
service YunPian {
rpc Send(SendSmsReq) returns (SendSmsRes);
}
message SendSmsReq {
string code = 1;
}
message SendSmsRes {
int32 code = 1;
string message = 2;
map data = 3;
}
参考链接: https://www.cnblogs.com/ghj1976/p/5435565.html
protoc --proto_path=examples/protos --php_out=examples/php/route_guide --grpc_out=examples/php/route_guide
--plugin=protoc-gen-grpc=bins/opt/grpc_php_plugin ./examples/protos/route_guide.proto
proto_path对应proto文件的位置,php_out指定生成PHP文件的目录,grpc_out和php_out指定相同的目录,plugin对应上面安装的grpc_php_plugin命令路径,最后跟上具体proto的文件地址。
syntax = "proto3";
package yunpian;
service YunPian {
rpc Send(SendSmsReq) returns (SendSmsRes);
}
message SendSmsReq {
string code = 1;
}
message SendSmsRes {
int32 code = 1;
string message = 2;
map data = 3;
}
通过protoc命令生成PHP文件
protoc --proto_path=examples/protos --php_out=examples/php/route_guide --grpc_out=examples/php/route_guide
--plugin=protoc-gen-grpc=bins/opt/grpc_php_plugin ./examples/protos/route_guide.proto
通过composer安装consule-php-sdk等包
"require": {
"grpc/grpc": "^v1.3.0",
"google/protobuf": "^v3.3.0",
"sensiolabs/consul-php-sdk": "^3.0"
},
require dirname(__FILE__).'/../vendor/autoload.php';
define('COORD_FACTOR', 1e7);
$serviceFactory = new SensioLabs\Consul\ServiceFactory();
$cl = $serviceFactory->get("catalog"); //采用cataLog的服务方式
$service = $cl->service("yunpian"); //参数传入和服务端约定的服务名
$microServiceData = \GuzzleHttp\json_decode($service->getBody(), true)[0]; //请求微服务的具体地址
$host = $microServiceData["ServiceAddress"];
$port = $microServiceData["ServicePort"];
$client = new Yunpian\YunPianClient($host.":".$port, [
'credentials' => Grpc\ChannelCredentials::createInsecure(),
]);
$reqObj = new Yunpian\SendSmsReq(); //自定义请求
$reqObj->setCode("1234");
list($data, $status) = $client->Send($reqObj)->wait();
var_dump($data->getCode());
var_dump($data->getMessage());
var_dump($data->getData());
源码:go-grpc-getway