gRPC是Google开源的一个高性能、跨语言的RPC框架,基于HTTP2协议,基于protobuf 3.x,基于Netty 4.x +。
gRPC与thrift、avro-rpc、WCF等其实在总体原理上并没有太大的区别,简而言之GRPC并没有太多突破性的创新。
protobuf相对于用Json方式传输,效率有很大提高,Kubernetes也从最初的Json转换成了gRPC。
gRPC 在服务端提供一个 gRPC Server,客户端的库是 gRPC Stub。
典型的场景是客户端发送请求,同步或异步调用服务端的接口。
gRPC在服务端和客户端可以使用多种语言,包括Go, Python, Java or Ruby等。
下面以GoLang为例,展示一个gRPC Client调用gRPC Server的整个过程:
1. 准备gRPC环境
1) 安装Go语言环境,gRPC要求Go 1.5或以上。
2) 安装gRPC
$ go get google.golang.org/grpc
3) 安装Protocol Buffers v3
下载protoc-3.0.0-linux-x86_64.zip:https://github.com/google/protobuf/releases
解压并拷贝bin/protoc到$GOPATH (/usr/local/go/bin)
4) 安装protoc plugin for Go
$ go get -u github.com/golang/protobuf/protoc-gen-go
拷贝bin/protoc-gen-go到$GOPATH (/usr/local/go/bin)
2. 编写helloworld.proto协议文件,简单完成一个加法运算
syntax = "proto3"; package helloworld; // The greeting service definition. service Greeter { // Sends a greeting rpc SayAdd (AddRequest) returns (AddReply) {} } // The request message containing the a+b. message AddRequest { uint32 a = 1; uint32 b =2; } // The response message containing the c. message AddReply { uint32 c = 1; }
3. 使用protoc-gen-go生成gRPC服务端和客户端代理文件helloworld.pb.go
$ protoc -I helloworld/ helloworld/helloworld.proto --go_out=plugins=grpc:helloworld
4. 编写gRPC服务端文件greeter_server/main.go
package main import ( "log" "net" "golang.org/x/net/context" "google.golang.org/grpc" pb "google.golang.org/grpc/examples/helloworld/helloworld" "google.golang.org/grpc/reflection" ) const ( port = ":50051" ) // server is used to implement helloworld.GreeterServer. type server struct{} // SayAdd implements helloworld.GreeterServer func (s *server) SayAdd(ctx context.Context, in *pb.AddRequest) (*pb.AddReply, error) { return &pb.AddReply{C: in.A + in.B}, nil } func main() { lis, err := net.Listen("tcp", port) if err != nil { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() pb.RegisterGreeterServer(s, &server{}) // Register reflection service on gRPC server. reflection.Register(s) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } }
5. 编写gRPC客户端文件greeter_client/main.go
package main import ( "log" "os" "golang.org/x/net/context" "google.golang.org/grpc" pb "google.golang.org/grpc/examples/helloworld/helloworld" ) const ( address = "localhost:50051" ) func main() { // Set up a connection to the server. conn, err := grpc.Dial(address, grpc.WithInsecure()) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() c := pb.NewGreeterClient(conn) // Contact the server and print out its response. rs, errs := c.SayAdd(context.Background(), &pb.AddRequest{A: 1, B:2}) if errs != nil { log.Fatalf("could not greet: %v", errs) } log.Printf("Add: %d", rs.C) }
6. 运行gRPC服务端
$ go run greeter_server/main.go
7. 运行gRPC客户端
$ go run greeter_client/main.go
输出结果: Add: 3
Demo下载地址:http://files.cnblogs.com/files/edisonxiang/helloworld.zip