Part 01 Golong 微服务教程:ProtoBuf 与 gRPC 初步使用

预置条件

我们需要下面准备工作:

1、安装protobuf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 源码安装

$ wget https://github.com/protocolbuffers/protobuf/releases/download/v3.6.1/protobuf-all-3.6.1.tar.gz
$ tar zxvf protobuf-all-3.6.1.tar.gz
$ cd protobuf-3.6.1/
$ ./autogen.sh
$ ./configure
$ make
$ make install
$ protoc -h

# 或者
$ git clone https://github.com/google/protobuf
$ cd protobuf
$ ./autogen.sh
$ ./configure
$ make
$ make check
$ sudo make install

2、安装 gRPC 框架

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

3、安装 Go 版本的 protobuf 编译器

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

开始代码编写

目录结构:

1
2
3
4
5
6
7
└── grpc-day01
├── client
│   └── client.go
├── proto
│   ├── user.pb.go
│   └── user.proto
└── server.go

1、定义 protobuf 通信协议文件 user.proto

编写 user.proto生成框架代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

syntax = "proto3";

package proto;

service UserService {
rpc Info (UserRequest) returns (UserResponse);
}

message UserRequest{
string id = 1;
}

message UserResponse{
string id = 1;
string name = 2;
string gender = 3;
string mobile = 4;
}

然后编译 user.proto 文件 生成 user.pb.go:

1
2
3
# protoc 编译器的 grpc 插件会处理 service 字段定义的 UserService
# 使 service 能编码、解码 message
$ protoc --go_out=plugins=grpc:. user.proto

2、 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

package main

import (
"context"
"net"

pb "github.com/entere/go-demos/grpc-day01/proto"
"google.golang.org/grpc"
)

// UserService ..
type UserService struct{}

// Info ..
func (s *UserService) Info(ctx context.Context, r *pb.UserRequest) (*pb.UserResponse, error) {

userResponse := &pb.UserResponse{Id: r.GetId(), Name: "entere", Gender: "1", Mobile: "138xxxxxxxx"}
return userResponse, nil
}

// PORT ..
const PORT = "9001"

func main() {
server := grpc.NewServer()
pb.RegisterUserServiceServer(server, &UserService{})

lis, err := net.Listen("tcp", ":"+PORT)
if err != nil {

}
server.Serve(lis)
}

3、client.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
package main

import (
"context"
"log"

pb "github.com/entere/go-demos/grpc-day01/proto"
"google.golang.org/grpc"
)

// PORT ..
const PORT = "9001"

func main() {
conn, err := grpc.Dial(":"+PORT, grpc.WithInsecure())
if err != nil {
log.Fatalf("grpc.Dial err: %v", err)
}

client := pb.NewUserServiceClient(conn)

resp, err := client.Info(context.Background(), &pb.UserRequest{Id: "1"})
if err != nil {
log.Fatalf("client.User err: %v", err)
}
log.Printf("resp: %v", resp)
}