GRPC入门

[TOC]

1. 编写消息并编译为go代码

1.1 安装

  1. 安装go vscode
  2. vscode安装protobuf插件
  3. 安装protoc,编写makefile生成go代码

1.2 protocol message规则

  1. message使用驼峰

  2. 字段使用lower_snake_case

  3. 内置的类型

    1. string, bool, bytes

    2. float, double

    3. int32, int64, uint32, uint64, sint32, sint64

  4. 也可以使用其他message作为字段类型

  5. tag很重要:

    1. tag整数,从1到2^29-1
    2. 19000-19999保留
    3. 第1-15个tag使用1个byte
    4. 16-2047个tag占用2个byte
    5. tag不需要有顺序或者递增tag必须唯一定义消息

1.3 消息定义

定义文件proto/processor_message.proto

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
syntax = "proto3";
option go_package="io.liux/pcbook/pb";

package pb;
message CPU {
// comment 1
string brand = 1;
/*
* comment 2
*/
string name = 2;
uint32 number_cores = 3;
uint32 number_threads = 4;
double min_ghz = 5;
double max_ghz = 6;
}

1.4 编译为Go

配置环境:

  1. 下载protochttps://github.com/protocolbuffers/protobuf/releases
  2. 按照https://grpc.io/docs/languages/go/quickstart/ 进行配置

编译:

protoc --go_out=. --go_opt=module=io.liux/pcbook --go-grpc_out=. --go-grpc_opt=paths=source_relative proto/*.proto