RPC是远程调用的简称, 简单的说就是要像调用本地函数一样调用服务器的函数,Protobuf 是 Google 公司开发的编码协议, 它的优势是编码后的数据体积比较小(并不是压缩算法), 比较适合用于命令的传输编码。Protobuf 官方团队提供 Java/C++/Python 几个语言的支持, Go语言的版本由Go团队提供支持, 其他语言由第三方支持。接下来我们体验一下go的grpc。
1 protoc安装protoc-3.20.0-win64.zip安装:
体验go的gRPC,首先我们需要下载工具protoc-3.20.0-win64.zip:
https://github.com/protocolbuffers/protobuf/releases 或直接点击 https://github.com/protocolbuffers/protobuf/releases/download/v3.20.0/protoc-3.20.0-win64.zip
windows环境下,下载后需要将压缩文件解压后放置在平时的软件安装文件夹,然后将其中的bin文件夹路径添加入系统环境变量中。之后win+R运行如下即安装完成:
2 下载go的依赖包go get github.com/golang/protobuf/protoc-gen-go3 proto文件
syntax = "proto3";
option go_package = ".;proto";
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
4 生成go文件,运行如下命令
protoc -I . 文件名.proto --go_out=plugins=grpc:.
相比于python运行proto后会生成两个grpc的py文件,go和java等其他语言只生成一个.pb文件。
5 server端代码
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"grpc_demo/hello"
"net"
)
type Server struct {
}
func (s *Server) SayHello(ctx context.Context,request *hello.HelloRequest)(*hello.HelloReply,error){
return &hello.HelloReply{Message:"Hello "+request.Name},nil
}
func main() {
g := grpc.NewServer()
s := Server{}
hello.RegisterGreeterServer(g,&s)
lis, err := net.Listen("tcp", fmt.Sprintf(":8080"))
if err != nil {
panic("failed to listen: "+err.Error())
}
g.Serve(lis)
}
6 client端代码
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"grpc_demo/proto"
)
func main() {
conn,err := grpc.Dial("127.0.0.1:8080",grpc.WithInsecure())
if err!=nil{
panic(err)
}
defer conn.Close()
c := hello.NewGreeterClient(conn)
r,err := c.SayHello(context.Background(),&hello.HelloRequest{Name:"babay"})
if err!=nil{
panic(err)
}
fmt.Println(r.Message)
}
7 运行服务端和客户端程序
运行结果:
Hello babay



