Laravel gRPC Client on Docker
參考資訊
https://ld246.com/article/1582954122248
https://www.kandaoni.com/news/36063.html
https://www.cnblogs.com/qing123/p/15144337.html
系統必要軟體
修改Dockerfile 增加以下,install grpc可能會跑超過1000秒以上需要一些時間
| 
					 1 2 3 4  | 
						#grpc RUN pecl install grpc RUN pecl install protobuf RUN apt-get install -yq protobuf-compiler  | 
					
修改php.ini,增加以下extension
| 
					 1 2  | 
						extension=grpc.so extension=protobuf.so  | 
					
專案套件
Laravel 專案中安裝以下套件
| 
					 1 2 3  | 
						composer require grpc/grpc composer require google/protobuf composer require ext-grpc  | 
					
gRPC資料準備
準備gRPC server端提供的proto 檔案,範例如下
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22  | 
						#notify_rpc.proto syntax = "proto3"; //package name package Notify; //service name service Notifier {   //function name   rpc send_message (NotifyRequest) returns (NotifyResponse); } //method1 message NotifyRequest {   string message = 1;   string platform = 2; } //method2 message NotifyResponse {   string message = 1; }  | 
					
在專案資料夾中建立以下資料夾
protobuf/build
protobuf/src
將notify_rpc.proto檔案放到protobuf/src中
執行以下指令生成相對應的php檔案
| 
					 1  | 
						protoc --proto_path=protobuf --php_out=protobuf/build protobuf/src/notify_rpc.proto  | 
					
–php_out指定生成的位置
最後一個參數告訴他proto檔案的位置在哪
這時候會看到專案資料夾/protobuf/build中產生了以下幾個檔案
| 
					 1 2 3  | 
						GPBMetadata/Src/NotifyRpc.php Notify/NotifyRequest.php Notify/NotifyResponse.php  | 
					
根據外部連結的說明文件來看,我們還缺一個 Nofity/NotifyClient.php檔案,原因是還需要透過grpc_php_plugin來生成,但是這個plugin一直build不起來
不過NofityClient.php不難,就手刻一個
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19  | 
						<?php //namespace 與NofityRequest.php中相同 namespace Notify; class NotifyClient extends \Grpc\BaseStub { public function __construct($hostname, $opts, $channel = null) { parent::__construct($hostname, $opts, $channel); } //send_message就是proto檔案中定義的,傳入值為NofityRequest,回傳值為NofityResponse public function send_message(\Notify\NotifyRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/Notify.Notifier/send_message', $argument, ['\Notify\NotifyResponse', 'decode'], $metadata, $options); } }  | 
					
gRPC服務呼叫
完成以上設定後就可以在Controller中呼叫Notify gRPC服務,範例如下
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27  | 
						<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Notify\NotifyRequest; use Notify\NotifyClient; use Grpc\ChannelCredentials; class IndexController extends Controller {     //     public function index(){         //grpc_test         $client = new NotifyClient('GRPC_SERVER_IP:PORT',[             'credentials' => ChannelCredentials::createInsecure(),         ]);         $request = new NotifyRequest();         //將需要傳送的兩個參數分別透過setMessage以及setPlatform加入         $request->setMessage('hello123');         $request->setPlatform('slack');         $get = $client->send_message($request)->wait();         return view('index');     } }  |