這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
1.安裝gRPC運行環境
go get google.golang.org/grpc
這裡的grpc通俗來說就說用在代碼裡的一個類庫,後面的例子可以看到。比較坑的是這裡可能需要FQ.....
2.安裝protoc
這裡需要安裝proto buffer
的編譯器。首先在官網下載,如c++版本的protobuf-cpp-3.4.1.tar.gz,解壓後進行編譯:
./configure make && make install
3.安裝protoc-gen-go
go get -a github.com/golang/protobuf/protoc-gen-go
4.編寫proto檔案
基於protobuf的跨語言的特性,不難想到它自己實現了一套資料類型。這裡有一個簡單的例子
//testHello.protosyntax = "proto3";package protos;// The service definition.service Devops { // 定義服務 rpc SayHello (HelloRequest) returns (Response) {}}// The request message containing the user's name.message HelloRequest { string name = 1;}// The response messagemessage HelloReply { string message = 1;}message Response { enum StatusCode { UNDEFINED = 0; SUCCESS = 200; FAILURE = 500; } StatusCode status = 1; HelloReply msg = 2;}
然後在終端自動產生pb.go:
protoc --go_out=plugins=grpc:. testHello.proto
5.編寫服務端
package mainconst ( port = ":50051")type myserver struct{}//這裡myserver實現了SayHellofunc (s *myserver) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.Response, error) { fmt.Print("receive " + in.Name) return &pb.Response{ Status:pb.Response_SUCCESS, Msg:&pb.HelloReply{Message:"receive " + in.Name}, }, nil}func main() { //綁定連接埠 lis, err := net.Listen("tcp", port) if err != nil{ log.Fatal("fail to listen") } s := grpc.NewServer() pb.RegisterDevopsServer(s, &myserver{}) s.Serve(lis)}
6.編寫用戶端
package mainconst ( address = "localhost:50051")func main() { //grpc.WithInsecure()指定後才不會報錯 conn, err := grpc.Dial(address, grpc.WithInsecure()) if err != nil{ log.Fatal("error....", err) } c := pb.NewDevopsClient(conn) res, _ := c.SayHello(context.Background(), &pb.HelloRequest{"eeee"}) fmt.Print(res)}
WithInsecure returns a DialOption which disables transport security for this ClientConn.
Note that transport security is required unless WithInsecure is set.
WithInsecure返回一個DialOption,它在傳輸過程中不保證安全。除非設定WithInsecure,否則grpc.Dial必須指定安全選項。
參考:
1.https://github.com/google/protobuf/releases
2.http://www.cnblogs.com/YaoDD/p/5504881.html