gRPC的PHP客戶端

工做中須要使用gRPC,服務端採用的python,客戶端採用PHP。這裏主要講述PHP客戶端。php

分爲如下幾個部分:python

  1. 安裝protoc
  2. 生成protobuf
  3. 安裝PHP擴展
  4. 定義客戶端

安裝protoc

這裏是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.protobash

syntax = "proto3";
package lotteryservice;
service Greeter {
    rpc lottery(lotteryReq) returns (lotteryRes){}
}

message lotteryReq {
    string param = 1;
}

message lotteryRes {
    string data = 1;
}

會生成以下目錄:app

clipboard.png

安裝PHP擴展

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 以後會生成以下目錄:

clipboard.png

在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

相關文章
相關標籤/搜索