這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
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,解壓後
./configuremake && 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 greetingsmessage 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.goimport ("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.goimport ("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 := defaultNameif 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.gogo run client.go