工做中须要使用gRPC,服务端采用的python,客户端采用PHP。这里主要讲述PHP客户端。php
分为如下几个部分:python
这里是mac环境git
下载地址:https://github.com/protocolbu...github
./autogen.sh
brew install automake
./autogen.sh
./configure --prefix=/usr/local/protobuf
make && make install
最后不要忘记配置环境变量json
vim ~/.bash_profile export PROTOBUF=/usr/local/protobuf export PATH=$PROTOBUF/bin:$PATH source ~/.bash_profile
验证vim
protoc --version
protobuf
文件使用服务端的.proto
文件,执行protoc --php_out=. lottery.proto
bash
syntax = "proto3"; package lotteryservice; service Greeter { rpc lottery(lotteryReq) returns (lotteryRes){} } message lotteryReq { string param = 1; } message lotteryRes { string data = 1; }
会生成以下目录:app
gRPC扩展: http://pecl.php.net/package/gRPC
protobuf扩展: http://pecl.php.net/package/p...composer
在项目目录下编写composer.json
测试
{ "name": "grpc-go-php", "require": { "grpc/grpc": "^v1.3.0", "google/protobuf": "^v3.3.0" }, "autoload":{ "psr-4":{ "GPBMetadata\\":"GPBMetadata/", "Lotteryservice\\":"Lotteryservice/" } } }
composer install
以后会生成以下目录:
在Lotteryservice文件夹中,建立lotteryServiceClient.php
<?php namespace Lotteryservice; class lotteryServiceClient extends \Grpc\BaseStub{ public function __construct($hostname, $opts, $channel = null) { parent::__construct($hostname, $opts, $channel); } public function lottery(\Lotteryservice\lotteryReq $argument, $metadata=[], $options=[]){ // (/Greeter/lottery) 是请求服务端那个服务和方法,基本和 proto 文件定义同样 // (\Lotteryservice\lotteryRes) 是响应信息(那个类),基本和 proto 文件定义同样 return $this->_simpleRequest('/Greeter/lottery', $argument, ['\Lotteryservice\lotteryRes', 'decode'], $metadata, $options); } }
建立channel
文件夹,在channel
文件夹下建立 channels.php
文件,获取client
<?php namespace channel; class channels { public function lotteryService() { $client = new \Lotteryservice\lotteryServiceClient('127.0.0.1:50051', [ 'credentials' => \Grpc\ChannelCredentials::createInsecure() ]); return $client; } }
在项目目录下建立app.php
,用于测试链接:
<?php //引入 composer 的自动载加 require __DIR__ . '/vendor/autoload.php'; $channels = new channel\channels(); $lotteryClient = $channels->lotteryService(); $lotteryRequest = new \Lotteryservice\lotteryReq(); $lotteryRequest->setParam('{"一等奖": 10,"二等奖":20,"三等奖":30,"四等奖":40}'); $lottery_res = $lotteryClient->lottery($lotteryRequest)->wait(); list($reply, $status) = $lottery_res; $data = $reply->getData(); var_dump($data);die;
最后执行php app.php