GO GRPC 安装
安装 protoc
下载 https://github.com/protocolbuffers/protobuf/releases/latest
$cd %GOPATH%
将解析的后的 protoc.exe 文件放入 %GOPATH%/bin
$protoc --version
安装 protoc-gen-go
$go get -u github.com/golang/protobuf/protoc-gen-go
或者手动安装
下载源码,解压到 %GOPATH%/src/github.com/golang 下
进入 %GOPATH%\src\github.com\golang\protobuf\protoc-gen-go
$go build
$go install
%GOPATH%/bin 下会有 protoc-gen-go.exe
安装 grpc-go
go get google.golang.org/grpc
PHP扩展
https://pecl.php.net/package/gRPC
php_grpc fastcgi 使用 nts , 非使用 ts
php.ini 添加 extension=grpc
https://pecl.php.net/package/protobuf
protobuf 没有windows版dll, 但有 composer 库 google/protobuf
Composer
php composer.phar require grpc/grpc
php composer.phar require google/protobuf
Protobuf3语言指南
Protobuf3语言指南_千念飞羽的专栏-CSDN博客_protobuf3
GO服务端
common.proto
syntax = "proto3";
package common;
option go_package = "common";
message Request {
string ping = 1;
}
message Response {
string pong = 1;
}
service Common {
rpc Ping(Request) returns(Response);
}
生成服务端代码
go mod init qgmvc/rpc/common
protoc --go_out=plugins=grpc:. common.proto
go mod tidy复制 common.pb.go 到 ./pb 目录下
在前目录下新建立一个 main.go 文件
main.go
package main
import (
"context"
"flag"
"fmt"
"log"
"net"
"strconv"
pb "qgmvc/rpc/common/pb"
"google.golang.org/grpc"
)
var (
port = flag.Int("port", 8301, "The server port")
)
//CommonServer.
type server struct {
pb.CommonServer
}
var regi int = 0
//方法
func (s *server) Ping(ctx context.Context, in *pb.Request) (*pb.Response, error) {
log.Printf("Received: %v", in.Ping+strconv.Itoa(regi))
regi++
return &pb.Response{Pong: "[" + in.Ping + strconv.Itoa(regi) + "]"}, nil
}
func main() {
flag.Parse()
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterCommonServer(s, &server{})
log.Printf("server listening at %v", lis.Addr())
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
服务端目录结构
启动服务端
go run main.go
PHP 客户端
生成
protoc --php_out=./php common.proto
目录结构
在 Common 中新建立一个 CommonClient.php 文件
CommonClient.php
<?php
namespace Common;
class CommonClient extends \Grpc\BaseStub{
public function __construct($hostname, $opts, $channel = null) {
parent::__construct($hostname, $opts, $channel);
}
public function Ping(\Common\Request $argument,$metadata=[],$options=[]){
#/common.Common/Ping 是请求服务端那个服务和方法
#\Common\Response 响应信息
return $this->_simpleRequest('/common.Common/Ping',
$argument,
['\Common\Response', 'decode'],
$metadata, $options);
}
}
调用
自行处理 Common 和 GPBMetadata 命名空间的自动加载
<?php
class indexAction extends \action
{
public function rpc($ping)
{
$client = new \Common\CommonClient('127.0.0.1:8301', [
'credentials' => \Grpc\ChannelCredentials::createInsecure()
]);
$request = new \Common\Request();
$request->setPing($ping);
//调用远程服务
$get = $client->Ping($request)->wait();
list($reply, $status) = $get;
$data = [
"code"=>0,
"message"=>$reply->getPong()
];
return $data;
}
}
qgmvc自动加载