Go gRPC体验

本文源码地址: https://github.com/zboyco/go-test/blob/master/gRPC


0 环境安装

protobuf

1
https://github.com/protocolbuffers/protobuf/releases

protoc-gen-go

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

gRPC

1
go get -u google.golang.org/grpc

1. 编写协议

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
syntax = "proto3";

package proto;

message HelloReq {
string name = 1;
}

message HelloRes {
string answer = 1;
}

service greeter {
rpc Hello (HelloReq) returns (HelloRes);
}

2. 生成Go代码

使用proto配合grpc插件生成Go代码:

1
protoc --go_out=plugins=grpc:. greeter.proto
  • go_out参数中要使用grpc插件,若不使用生成的代码不会包含grpc方法.

3. 编写服务(Server)

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
package main

import (
"context"
"fmt"
"net"

"google.golang.org/grpc"

"github.com/zboyco/go-test/gRPC/proto"
)

type server struct{}

func (s *server) Hello(c context.Context, req *proto.HelloReq) (*proto.HelloRes, error) {
return &proto.HelloRes{
Answer: "Hello " + req.Name,
}, nil
}

func main() {
lis, err := net.Listen("tcp", ":9043")
if err != nil {
fmt.Println(err)
return
}
s := grpc.NewServer()
proto.RegisterGreeterServer(s, &server{})
s.Serve(lis)
}

4. 编写客户端(Client)

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
package main

import (
"context"
"fmt"

"github.com/zboyco/go-test/gRPC/proto"
"google.golang.org/grpc"
)

func main() {
conn, err := grpc.Dial("localhost:9043", grpc.WithInsecure())
if err != nil {
fmt.Println(err)
return
}
defer conn.Close()

c := proto.NewGreeterClient(conn)

for i := 0; i < 10; i++ {
res, err := c.Hello(context.TODO(),
&proto.HelloReq{
Name: fmt.Sprintf("baiyang-%v", i),
},
)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(res.Answer)
}

}

5. 运行结果

先运行server,然后运行client

1
2
3
4
5
6
7
8
9
10
11
❯ go run main.go
Hello baiyang-0
Hello baiyang-1
Hello baiyang-2
Hello baiyang-3
Hello baiyang-4
Hello baiyang-5
Hello baiyang-6
Hello baiyang-7
Hello baiyang-8
Hello baiyang-9

over