grpc 高性能的开源rpc框架,基于HTTP/2标准设计,带来诸如双向流、流控、头部压缩、单tcp连接的多路复用请求
rpc remote procedure calls 远程过程调用
"google.golang.org/grpc"
proto文件
syntax = "proto3";
option go_package = ".iservice";
message HelloRequest {
string name = 1;
}
message HelloResponse{
string greeting = 1;
}
service HelloService {
rpc SayHello(HelloRequest) return (HelloResponse) {}
}
1.protoc 下载地址 https://github.com/protocolbuffers/protobuf/releases
protoc-27.3-win64.zip 解析 将protoc.exe 路径加入环境变量 path中
2.检查protoc 版本,cmd-> protoc --version
3.把解压的protoc.exe文件拷贝到GOPATH/bin目录下
4.打开 go mod,执行go env -w GO111MODULE=on
修改goproxy,go env -w GOPROXY=https://goproxy.cn,direct
5.下载protoc-gen-go,是 Protocol Buffers 的 Go 语言编译器插件,用于将 .proto
文件编译成 Go 语言可以理解的代码
go install github.com/golang/protobuf/protoc-gen-go@latest
protoc-gen-go.exe 被放入gopath下的bin目录下,将该目录放入path中
执行 source ~/.bashrc,或重新打开终端,使环境变量修改生效
6 执行命令 protoc --go_out=plugins=grpc:./ hello.proto ,消息文件和rpc文件合并生成 hello.pb.go 文件
该命令protoc 调用proto-gen-go插件执行
=========== grpc_service ===================================
新建文件夹 hello_service,执行 go mod init helloService,生成 go.mod 文件 (goland-setting-gopath 中加入hello_service 目录)
go get -u google.golang.org/grpc 或者 调用后,执行go mod tidy 补全引用包
package main import ( "context" "fmt" "google.golang.org/grpc" "helloService/src/pb" "net" ) type HelloService struct { } func (hs *HelloService) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloResponse, error) { resp := &pb.HelloResponse{ Greeting: fmt.Sprintf("hello %s from hello client", req.Name), } return resp, nil } func main() { fmt.Println("aaa") listen, err := net.Listen("tcp", "127.0.0.1:50051") if err != nil { fmt.Println("error happend when listen on 127.0.0.1:50051", err) return } s := grpc.NewServer() pb.RegisterHelloServiceServer(s, &HelloService{}) fmt.Println("golang rpc server is waiting message.....") if err = s.Serve(listen); err != nil { fmt.Println("error happend when start rpc server:", err) return } }
====== grpc_client ===================================
package main import ( "context" "fmt" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "helloClient/src/pb" "time" ) func main() { conn, err := grpc.Dial("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { fmt.Println("helloClient dial happend error: ", err) return } defer conn.Close() c := pb.NewHelloServiceClient(conn) ctx, cancel := context.WithTimeout(context.Background(), time.Second*2) defer cancel() req := &pb.HelloRequest{Name: "guoxh"} res, err := c.SayHello(ctx, req) if err != nil { fmt.Println("error happend when sayHello: ", err) return } fmt.Println("get response: ", res) }