1. 程式人生 > >grpc go安裝教程

grpc go安裝教程

客戶端 ogl gop 獲取 pat pro server tcp tps

  安裝protobuf

go get -u github.com/golang/protobuf/proto

go get -u github.com/golang/protobuf/protoc-gen-go

此時會生成protoc-gen-go,protoc一般是獲取已經編譯好的可執行文件(https://github.com/google/protobuf/releases)

  安裝gRPC

go get -u google.golang.org/grpc

不過由於國內的網絡原因上面的命令可能不會成功

執行下面的多條命令來代替

git clone https://github.com/golang/net.git $GOPATH/src/golang.org/x/net

git clone https://github.com/golang/text.git $GOPATH/src/golang.org/x/text

git clone https://github.com/google/go-genproto.git $GOPATH/src/google.golang.org/genproto

git clone https://github.com/grpc/grpc-go.git $GOPATH/src/google.golang.org/grpc

如果 $GOPATH中有多個路徑,請手動替換成其中一個。

  測試案例

HelloService.proto和之前C++編譯教程的一樣

生成命令如下:

protoc HelloService.proto -I . --go_out=. 這個是僅僅生成protobuf的產物

protoc HelloService.proto -I . --go_out=plugins=grpc:.

生成的HelloService.pb.go 需要改成package main

server.go

 1 package main
 2 
 3 import (
 4     "context"
 5     "fmt"
 6     "net"
 7 
 8     "google.golang.org/grpc
" 9 ) 10 11 type HelloServiceServerImpl struct { 12 } 13 14 func (s *HelloServiceServerImpl) SayHello(c context.Context, req *Request) (*Response, error) { 15 fmt.Printf("%s\n", string(req.Data)) 16 17 resp := Response{} 18 resp.Data = []byte("hello from server") 19 20 return &resp, nil 21 } 22 23 func main() { 24 lis, err := net.Listen("tcp", "127.0.0.1:57501") 25 if err != nil { 26 fmt.Println(err) 27 return 28 } 29 s := grpc.NewServer() 30 RegisterHelloServiceServer(s, &HelloServiceServerImpl{}) 31 fmt.Printf("Server listening on 127.0.0.1:57501\n") 32 s.Serve(lis) 33 }

client.go

 1 package main
 2 
 3 import (
 4     "context"
 5     "fmt"
 6 
 7     "google.golang.org/grpc"
 8 )
 9 
10 func main() {
11     conn, err := grpc.Dial("127.0.0.1:57501", grpc.WithInsecure())
12     if err != nil {
13         fmt.Println(err)
14     }
15     client := NewHelloServiceClient(conn)
16     r, err := client.SayHello(context.Background(), &Request{Data: []byte("send from client")})
17     fmt.Printf("%s\n", string(r.Data))
18 }

使用go build -o client HelloService.pb.go client.go編譯

C++版本的服務器技術分享圖片

Go客戶端技術分享圖片

grpc go安裝教程