PHP|PHP中使用gRPC客户端

因为工作需要使用gRPC,本人使用的是windows10,不过linux的操作流程基本一样。
直接进入主题,分为了几部分
1、下载Protoc
下载地址:https://github.com/google/protobuf/releases
这里采用的二进制文件,选择对应的平台,下载
https://github.com/protocolbuffers/protobuf/releases/download/v3.7.1/protoc-3.7.1-win64.zip
【PHP|PHP中使用gRPC客户端】解压后得到,在bin文件夹下的 protoc.exe。我放到 D:\Program Files\protoc-3.7.1-win64\bin 下,并加入到系统环境变量 Path 中,就可以使用 protoc 命令了,可以用 protoc --version 来查看是否成功。(这一步很重要用于生成 protobuf 文件对应的 PHP代码 用的)
PHP|PHP中使用gRPC客户端
文章图片

PHP|PHP中使用gRPC客户端
文章图片

2、编写 protocol buffers 文件
如何编写请看 Protobuf3语言指南 写得不错,首先创建一个为 testgrpc_com 项目,我这的位置是 E:\www\testgrpc_com ,在项目下简单写了一个 xuexitest.proto

syntax = "proto3"; // 指定proto版本package xuexitest; // 指定包名//定义 Xuexitest 服务 service Xuexitest { //定义 SayTest 方法 rpc SayTest(TestRequest) returns (TestReply) {} }//TestRequest 请求结构 message TestRequest { int64 typeid = 1; }//TestReply 响应结构 message TestReply {//返回数据类型 message GetData { int64 id = 1; string name = 2; }repeated GetData getdataarr = 1; }

3、下载 PHP的gRPC扩展和protobuf扩展
PHP的gRPC扩展:http://pecl.php.net/package/gRPC
PHP的protobuf扩展: http://pecl.php.net/package/protobuf
注:1、PHP的protobuf扩展没有windows版本的,但不影响使用无非就是运行速度慢点。(使用 composer 加载 protobuf 类库,请看下面的 composer.json 配置文件)
注:2、如何安装PHP扩展,这里就不讲了。
4、编译 protocol buffers 文件
编译 xuexitest.proto 使用 protoc --php_out=. xuexitest.proto 会生成得到:
PHP|PHP中使用gRPC客户端
文章图片

5、使用 PHP 的 composer
首先 安装 composer 来管理和加载PHP的类库,如何安装这里就不讲了。(这一步也很重要用于解决 Grpc和 protobuf 的PHP类库依赖)
在项目下编写 composer.json 放到刚刚编译 protocol buffers 文件同级下
{ "name": "grpc-go-php", "require": { "grpc/grpc": "^v1.3.0", "google/protobuf": "^v3.3.0" }, "autoload":{ "psr-4":{ "GPBMetadata\\":"GPBMetadata/", "Xuexitest\\":"Xuexitest/" } } }

PHP|PHP中使用gRPC客户端
文章图片

6、使用 Composer 下载 PHP 代码
1.进入到项目的目录,如:E:\www\testgrpc_com 中在地址栏输入cmd回车即可
PHP|PHP中使用gRPC客户端
文章图片

2.在命令提示符(黑窗口)下输入 composer install 回车,等待下载完成。
PHP|PHP中使用gRPC客户端
文章图片

7、定义PHP的gRPC端户端
在项目的 Xuexitest 文件夹中,新建 XuexitestClient.php 文件
_simpleRequest('/xuexitest.Xuexitest/SayTest', $argument, ['\Xuexitest\TestReply', 'decode'], $metadata, $options); }}

PHP|PHP中使用gRPC客户端
文章图片

8、编写PHP执行文件
在项目下 新建 xuexitest.php
?php //引入 composer 的自动载加 require __DIR__ . '/vendor/autoload.php'; //用于连接 服务端 $client = new \Xuexitest\XuexitestClient('127.0.0.1:50052', [ 'credentials' => Grpc\ChannelCredentials::createInsecure() ]); //实例化 TestRequest 请求类 $request = new \Xuexitest\TestRequest(); $request->setTypeid(1); //调用远程服务 $get = $client->SayTest($request)->wait(); //返回数组 //$reply 是 TestReply 对象 //$status 是数组 list($reply, $status) = $get; //数组 $getdata = https://www.it610.com/article/$reply->getGetdataarr(); foreach ($getdata as $k=>$v){ echo $v->getId(),'=>',$v->getName(),"\n\r"; }

9、赶快执行下
PHP|PHP中使用gRPC客户端
文章图片

这是源代码:https://github.com/laixhe/php_grpc

    推荐阅读