grpc go安装教程

grpc go安装教程,第1张

概述  安装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)   安装gR

  安装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,nil21 }22 23 func main() {24     lis,err := net.Listen("tcp","127.0.0.1:57501")25     if err != nil {26         fmt.Println(err)27         return28     }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安装教程全部内容,希望文章能够帮你解决grpc go安装教程所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1209851.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-04
下一篇2022-06-04

发表评论

登录后才能评论

评论列表(0条)

    保存