工做中須要使用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