golang grpc demo
生活随笔
收集整理的這篇文章主要介紹了
golang grpc demo
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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 安裝(運(yùn)行時(shí)需要的依賴,下載完移動(dòng)到相應(yīng)的目錄里面)
git https://github.com/googleapis/go-genproto.git5.protoc?查看版本:
[root@wangjq]# protoc --version libprotoc 3.10.0?6.目錄結(jié)構(gòu):
[root@wangjq demo]# tree . ├── client │?? └── main.go ├── example │?? └── data.proto └── server└── main.go3 directories, 4 files7.data.proto 內(nèi)容如下
syntax = "proto3"; //指定proto版本 package proto;//定義請(qǐng)求結(jié)構(gòu) message HelloRequest{string name=1; }//定義響應(yīng)結(jié)構(gòu) message HelloReply{string message=1; }//定義Hello服務(wù) service Hello{//定義服務(wù)中的方法 rpc SayHello(HelloRequest) returns (HelloReply){} }8.生成 data.pb.go 文件
protoc -I . --go_out=plugins=grpc:. ./data.proto9.服務(wù)端代碼
package mainimport (pb "demo/example""fmt""golang.org/x/net/context""google.golang.org/grpc""net" )const (//gRPC服務(wù)地址Address = "127.0.0.1:50052" )//定義一個(gè)helloServer并實(shí)現(xiàn)約定的接口 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)}//實(shí)現(xiàn)gRPC Servers := grpc.NewServer()//注冊(cè)helloServer為客戶端提供服務(wù)pb.RegisterHelloServer(s, HelloServer) //內(nèi)部調(diào)用了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服務(wù)器conn, err := grpc.Dial(Address, grpc.WithInsecure())if err != nil {fmt.Println(err)} defer conn.Close()//初始化客戶端c := pb.NewHelloClient(conn)//調(diào)用方法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.運(yùn)行測(cè)試
服務(wù)端運(yùn)行: [root@wangjq demo]# go run server/main.go Listen on127.0.0.1:50052客戶端運(yùn)行: [root@wangjq demo]# go run client/main.go hellogRPC.?
轉(zhuǎn)載于:https://www.cnblogs.com/wangjq19920210/p/11572283.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的golang grpc demo的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: golang rpc demo
- 下一篇: YouCompleteMe unavai