protobuf简介
Protocol Buffers(protobuf)protobufprotobufprotoc.protoprotobufprotoc.protoprotobuf runtime libraryprotobuf runtimeprotobufprotobufruntime libraryprotobufgRPCgrpc-goprotobuf runtimeprotobuf runtimeprotobuf runtimev1.4gRPC-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 --versiongo install google.golang.org/protobuf/cmd/protoc-gen-go@latestgo install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latestprotoc-gen-goprotoc-gen-go-grpcgithub.com/golang/protobufprotoc-gen-gogoogle.golang.org/protobufprotoc-gen-goprotoc-gen-gov1.20v1.20protoc-gen-goprotoc-gen-goprotoc-gen-go-grpcgithub.com/golang/protobufprotoc-gen-go官方示例
下载代码
grpc-gogrpc-go/examples/helloworldgit clone -b v1.41.0 https://github.com/grpc/grpc-go
cd grpc-go/examples/helloworld运行代码
go run greeter_server/main.go2022/01/02 13:01:08 server listening at [::]:50051go run greeter_client/main.go2022/01/02 13:01:25 Greeting: Hello world工程开发
protobufgrpc-go.protoprotoc.protoxx.pb.goxx_grpc.pb.gogrpc-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.protofunc (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.gogo run greeter_client/main.go Alice客户端会打印如下内容:
2022/01/02 13:37:58 Greeting: Hello alice
2022/01/02 13:37:58 Greeting: Hello again aliceprotobufgRPC进阶学习
protobufgRPCprotobufgRPC开源地址
文章和示例代码开源地址在GitHub: https://github.com/jincheng9/go-tutorial
公众号:coding进阶