windows php(laravel) grpc client 实战步骤
1.项目根目录composer.json文件"require": 节点添加下面这2个
"grpc/grpc": "~1.30.0",
"google/protobuf": "~v3.12.2"
然后执行更新命令composer update
2.下载grpc+protobuf的windows版本,因为官网上面的教程都是针对的linux系统做的指引。windows的话需要自己编译,还好github上面已经有大佬编译好了,
https://github.com/lifenglsf/grpc_for_windows,
上面这个地址下载下,比如保存到e:\grpc_for_windows-master
3.建立proto文件,例如:GrpcService.proto
syntax = "proto3";
package WxGrpc;
service GrpcService{
rpc Chat(ChatRequest) returns(ChatResponse);
}
message ChatRequest{
string Receiver = 1;
string Content = 2;
}
message ChatResponse{
int32 Status = 1;
string Msg = 2;
}
4.命令行下切到php项目根目录,然后执行下面命令
"E:\grpc_for_windows-master\x64\protoc.exe" --proto_path="protos文件目录" --php_out=生成的php文件要存放的目录 --grpc_out=生成的php文件要存放的目录 --plugin=protoc-gen-grpc=E:\grpc_for_windows-master\x64\grpc_php_plugin.exe GrpcService.proto
5.完成后就可以写GrpcClient代码了
<?
namespace App\Extend;
class QsGrpcClient{
private $client;
private $response=["code"=>-1,"msg"=>""];
public function __construct(){
$this->client = new \WxGrpc\GrpcServiceClient("127.0.0.1:12828",[
'credentials' => \Grpc\ChannelCredentials::createInsecure(),
]);
}
public function chat($receive,$content){
$chatRequest=new \WxGrpc\ChatRequest();
$chatRequest->setReceiver("Qs");
$chatRequest->setContent("Haha");
$resp = $this->client->Chat($chatRequest)->wait();
return $this->handle($resp);
}
private function handle($resp){
list($result, $status) = $resp;
if($status->code){
$this->response["code"]=$status->code;
$this->response["msg"]=$status->details;
return false;
}
return $result;
}
public function getResponse(){
return $this->response;
}
}
?>