1、安裝gRPC runtime
go get google.golang.org/grpc
為了自動生成Golang的gRPC代碼,需要安裝protocal buffers compiler以及對應的GoLang插件
2、protocal buffer安裝
從https://github.com/google/protobuf/releases下載安裝包,例如:protobuf-cpp-3.0.0-beta-3.zip,解壓后
./configure make && make install
再添加環境變量:export LD_LIBRARY_PATH=/usr/local/lib,之后protoc命令即可運行
3、安裝GoLang protoc 插件
go get -a github.com/golang/protobuf/protoc-gen-go
4、定義service
一個RPC service就是一個能夠通過參數和返回值進行遠程調用的method,我們可以簡單地將它理解成一個函數。因為gRPC是通過將數據編碼成protocal buffer來實現傳輸的。因此,我們通過protocal buffers interface definitioin language(IDL)來定義service method,同時將參數和返回值也定義成protocal buffer message類型。具體實現如下所示,包含下面代碼的文件叫helloworld.proto:
syntax = "proto3"; option java_package = "io.grpc.examples"; package helloworld; // The greeter service definition. service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {} } // The request message containing the user's name. message HelloRequest { string name = 1; } // The response message containing the greetings message HelloReply { string message = 1; }
5、接着,根據上述定義的service,我們可以利用protocal buffer compiler ,即protoc生成相應的服務器端和客戶端的GoLang代碼。生成的代碼中包含了客戶端能夠進行RPC的方法以及服務器端需要進行實現的接口。
假設現在所在的目錄是$GOPATH/src/helloworld/helloworld,我們將通過如下命令生成gRPC對應的GoLang代碼:
protoc --go_out=plugins=grpc:. helloworld.proto
此時,將在目錄下生成helloworld.pb.go文件。
6、接着,在目錄$GOPATH/src/helloworld/下創建server.go 和client.go,分別用於服務器和客戶端的實現。
package main // server.go import ( "log" "net" "golang.org/x/net/context" "google.golang.org/grpc" pb "helloworld/helloworld" ) const ( port = ":50051" ) type server struct {} func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { return &pb.HelloReply{Message: "Hello " + in.Name}, nil } func main() { lis, err := net.Listen("tcp", port) if err != nil { log.Fatal("failed to listen: %v", err) } s := grpc.NewServer() pb.RegisterGreeterServer(s, &server{}) s.Serve(lis) }
package main //client.go import ( "log" "os" "golang.org/x/net/context" "google.golang.org/grpc" pb "helloworld/helloworld" ) const ( address = "localhost:50051" defaultName = "world" ) func main() { conn, err := grpc.Dial(address, grpc.WithInsecure()) if err != nil { log.Fatal("did not connect: %v", err) } defer conn.Close() c := pb.NewGreeterClient(conn) name := defaultName if len(os.Args) >1 { name = os.Args[1] } r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name}) if err != nil { log.Fatal("could not greet: %v", err) } log.Printf("Greeting: %s", r.Message) }
這里需要注意的是包pb是我們之前生成的helloworld.pb.go所在的包,並非必須如上述代碼所示在$GOPATH/src/helloworld/helloworld目錄下。
7、最后運行如下代碼進行演示即可
go run server.go go run client.go