protobuf简介

Protocol Buffers(protobuf)
protobuf
protobufprotoc.protoprotobufprotoc.protoprotobuf runtime libraryprotobuf runtimeprotobufprotobufruntime libraryprotobufgRPCgrpc-goprotobuf runtimeprotobuf runtimeprotobuf runtimev1.4

gRPC-Go简介

gRPC-Go: gRPC的Go语言实现,基于HTTP/2的RPC框架。

Go项目里导入该模块的方式如下:

import "google.golang.org/grpc"
grpc-goprotoc-gen-go-grpc.protoxx_grpc.pb.go

环境安装

分为3步:

protoc --version
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
protoc-gen-goprotoc-gen-go-grpc
github.com/golang/protobufprotoc-gen-gogoogle.golang.org/protobufprotoc-gen-goprotoc-gen-gov1.20v1.20protoc-gen-go
protoc-gen-goprotoc-gen-go-grpcgithub.com/golang/protobufprotoc-gen-go

官方示例

下载代码

grpc-gogrpc-go/examples/helloworld
git clone -b v1.41.0 https://github.com/grpc/grpc-go
cd grpc-go/examples/helloworld

运行代码

go run greeter_server/main.go
2022/01/02 13:01:08 server listening at [::]:50051
go run greeter_client/main.go
2022/01/02 13:01:25 Greeting: Hello world

工程开发

protobufgrpc-go
.protoprotoc.protoxx.pb.goxx_grpc.pb.go
grpc-go/examples/helloworld
// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
  // send another greeting
  rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}
protoc --go_out=. --go_opt=paths=source_relative \
    --go-grpc_out=. --go-grpc_opt=paths=source_relative \
    helloworld/helloworld.proto
func (s *server) SayHelloAgain(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
    log.Printf("Received: %v", in.GetName())
    return &pb.HelloReply{Message: "Hello again " + in.GetName()}, nil
}
r2, err2 := c.SayHelloAgain(ctx, &pb.HelloRequest{Name: *name})
if err2 != nil {
    log.Fatalf("could not greet: %v", err2)
}
log.Printf("Greeting: %s", r2.GetMessage())
go run greeter_server/main.go
go run greeter_client/main.go Alice

客户端会打印如下内容:

2022/01/02 13:37:58 Greeting: Hello alice
2022/01/02 13:37:58 Greeting: Hello again alice
protobufgRPC

进阶学习

protobufgRPC
protobufgRPC

开源地址

文章和示例代码开源地址在GitHub: https://github.com/jincheng9/go-tutorial

公众号:coding进阶

References