grpc golang學習心得(1)----安裝與測試

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

go語言小白,最近開始接觸grpc,特此記錄一下。

                                                                                                                                                                                                                                                                                      

1.grpc安裝

GRPC是一個高效能、開源、通用的RPC架構,面向移動和HTTP/2設計,是由Google發布的首款基於Protocol Buffers的RPC架構。

目前grpc提供C、JAVA、GO語言版本,其代碼都託管於github上,分別是:grpc, grpc-java, grpc-go。其中C版本支援C,C++,Node.js,Python,Ruby,Objective-C,PHP 和 C#。

本文只介紹grpc-go的安裝及使用。

1.1 檢查go語言版本

$go versiongo version go1.6.3 linux/amd64

grpc要求go語言版本至少為1.5+,版本過低的請先更新go語言版本:Getting Started - The Go Programming Language

1.2安裝grpc

$ go get google.golang.org/grpc

1.3安裝Protocol Buffers v3

protocol buffer是用來產生gRPC服務代碼的。

安裝GO的protoc外掛程式:

$ go get -u github.com/golang/protobuf/{proto,protoc-gen-go}
編譯器外掛程式protoc-gen-go安裝在$GOBIN目錄下,為了確保編譯器protoc能找到protoc-gen-go外掛程式,所以將$GOPATH匯入$PATH路徑下:

export PATH=$PATH:$GOPATH/bin
echo $PATH     //查看$PATH

*****gRPC安裝完成!


2.測試grpc

2.1定義service


一個RPC service就是一個能夠通過參數和傳回值進行遠程調用的method,我們可以簡單地將它理解成一個函數。因為gRPC是通過將資料編碼成protocal buffer來實現傳輸的。因此,我們通過protocal buffers interface definitioin language(IDL)來定義service method,同時將參數和傳回值也定義成protocal buffer message類型。具體實現如下所示,建立一個helloworld檔案夾,編輯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;}

2.2利用protocal buffer compiler產生對應的Golang代碼

根據上述定義的service,我們可以利用protocal buffer compiler ,即protoc產生相應的伺服器端和用戶端的GoLang代碼。產生的程式碼中包含了用戶端能夠進行RPC的方法以及伺服器端需要進行實現的介面。

假設現在所在的目錄是$GOPATH/src/helloworld/helloworld,我們將通過如下命令產生gRPC對應的GoLang代碼:

protoc --go_out=plugins=grpc:. helloworld.proto
此時,將在目錄下產生helloworld.pb.go檔案。

2.3測試gRPC服務

在目錄$GOPATH/src/helloworld/下建立server.go 和client.go,分別用於伺服器和用戶端的實現。

server.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)}

client.go

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目錄下。

2.4運行server/client.go
$ go run greeter_client/main.go

go run server.go
//重新開啟一個終端go run client.go

2.5

注意:如果你是通過go get google.golang.org/grpc安裝的grpc,在$GOPATH/src/google.golang.org/grpc/examples目錄下已經包含該測試案例

切換到examples目錄下
$ cd $GOPATH/src/google.golang.org/grpc/examples/helloworld
運行server/client.go
$ go run greeter_server/main.go
$ go run greeter_client/main.go
運行成功,會在client的終端輸出:Greeting: Hello world


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.