Golang gRPC 示例
Golang gRPC 示例
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-go4、定義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 greetingrpc 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,分別用于服務器和客戶端的實現。
packagemain// server.goimport("log""net""golang.org/x/net/context""google.golang.org/grpc"pb"helloworld/helloworld" )const(port =":50051" )typeserverstruct {}func(s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {return&pb.HelloReply{Message:"Hello "+ in.Name}, nil }funcmain() {lis, err := net.Listen("tcp", port)iferr != nil {log.Fatal("failed to listen: %v", err)}s := grpc.NewServer()pb.RegisterGreeterServer(s, &server{})s.Serve(lis) }packagemain//client.goimport("log""os""golang.org/x/net/context""google.golang.org/grpc"pb"helloworld/helloworld" )const(address ="localhost:50051"defaultName ="world" )funcmain() {conn, err := grpc.Dial(address, grpc.WithInsecure())iferr != nil {log.Fatal("did not connect: %v", err)}deferconn.Close()c := pb.NewGreeterClient(conn)name := defaultNameiflen(os.Args) >1 {name = os.Args[1]}r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})iferr != 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總結
以上是生活随笔為你收集整理的Golang gRPC 示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Go 的 flag 包可以解析命令行的参
- 下一篇: Golang 解决no buildabl