golang grpc demo
生活随笔
收集整理的這篇文章主要介紹了
golang grpc demo
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.grpm 安裝:
git clone https://github.com/grpc/grpc-go.git $GOPATH/src/google.golang.org/grpc2.proto, protoc-gen-go 安裝:
go get -u github.com/golang/protobuf/{proto,protoc-gen-go}3.protoc 安裝:
git clone https://github.com/protocolbuffers/protobuf.git cd $GOPATH/src/github.com/protocolbuffers/ ./autogen.sh ./configure make -j12 make install4.go-genproto 安裝(運行時需要的依賴,下載完移動到相應的目錄里面)
git https://github.com/googleapis/go-genproto.git5.protoc?查看版本:
[root@wangjq]# protoc --version libprotoc 3.10.0?6.目錄結構:
[root@wangjq demo]# tree . ├── client │?? └── main.go ├── example │?? └── data.proto └── server└── main.go3 directories, 4 files7.data.proto 內容如下
syntax = "proto3"; //指定proto版本 package proto;//定義請求結構 message HelloRequest{string name=1; }//定義響應結構 message HelloReply{string message=1; }//定義Hello服務 service Hello{//定義服務中的方法 rpc SayHello(HelloRequest) returns (HelloReply){} }8.生成 data.pb.go 文件
protoc -I . --go_out=plugins=grpc:. ./data.proto9.服務端代碼
package mainimport (pb "demo/example""fmt""golang.org/x/net/context""google.golang.org/grpc""net" )const (//gRPC服務地址Address = "127.0.0.1:50052" )//定義一個helloServer并實現約定的接口 type helloService struct{}func (h helloService) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {resp := new(pb.HelloReply)resp.Message = "hello" + in.Name + "." return resp, nil }var HelloServer = helloService{}func main() {listen, err := net.Listen("tcp", Address)if err != nil {fmt.Printf("failed to listen:%v", err)}//實現gRPC Servers := grpc.NewServer()//注冊helloServer為客戶端提供服務pb.RegisterHelloServer(s, HelloServer) //內部調用了s.RegisterServer()fmt.Println("Listen on" + Address)s.Serve(listen) }10.客戶端代碼
package mainimport (pb "demo/example""fmt""golang.org/x/net/context""google.golang.org/grpc" )const (Address = "127.0.0.1:50052" )func main() {//連接gRPC服務器conn, err := grpc.Dial(Address, grpc.WithInsecure())if err != nil {fmt.Println(err)} defer conn.Close()//初始化客戶端c := pb.NewHelloClient(conn)//調用方法reqBody := new(pb.HelloRequest)reqBody.Name = "gRPC"r, err := c.SayHello(context.Background(), reqBody)if err != nil {fmt.Println(err)}fmt.Println(r.Message) }11.運行測試
服務端運行: [root@wangjq demo]# go run server/main.go Listen on127.0.0.1:50052客戶端運行: [root@wangjq demo]# go run client/main.go hellogRPC.?
轉載于:https://www.cnblogs.com/wangjq19920210/p/11572283.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的golang grpc demo的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: golang rpc demo
- 下一篇: YouCompleteMe unavai