gRPC go安装教程

释放双眼,带上耳机,听听看~!

安装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)

linux需要将protoc-gen-go放到/usr/bin/,windows因为$GOPATH/bin已经加到PATH中了所以可以直接找到

安装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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
11 package main
2 2
3 3 import (
4 4     "context"
5 5     "fmt"
6 6     "net"
7 7
8 8     "google.golang.org/grpc"
9 9 )
1010
1111 type HelloServiceServerImpl struct {
1212 }
1313
1414 func (s *HelloServiceServerImpl) SayHello(c context.Context, req *Request) (*Response, error) {
1515     fmt.Printf("%s\n", string(req.Data))
1616
1717     resp := Response{}
1818     resp.Data = []byte("hello from server")
1919
2020     return &resp, nil
2121 }
2222
2323 func main() {
2424     lis, err := net.Listen("tcp", "127.0.0.1:57501")
2525     if err != nil {
2626         fmt.Println(err)
2727         return
2828     }
2929     s := grpc.NewServer()
3030     RegisterHelloServiceServer(s, &HelloServiceServerImpl{})
3131     fmt.Printf("Server listening on 127.0.0.1:57501\n")
3232     s.Serve(lis)
3333 }
34

client.go


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

使用go build -o client HelloService.pb.go client.go编译

C++版本的服务器gRPC go安装教程

Go客户端gRPC go安装教程

 

转载于:https://www.cnblogs.com/skyend/p/10838205.html

给TA打赏
共{{data.count}}人
人已打赏
安全经验

Google Adsense广告CPC(单元点击价格)为什么会减少??

2021-10-11 16:36:11

安全经验

安全咨询服务

2022-1-12 14:11:49

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索