一、Protobuf安装
下载地址:Protocol Buffers
比如,我们下载3.14.0,下载地址为:
https://github.com/protocolbuffers/protobuf/releases?expanded=true&page=4&q=v3.14.0
根据我们的电脑系统下载对应的二进制包,一般解压到GOPATH/bin目录下。
这里有个地方要注意,下载的文件中有个README文件
Protocol Buffers - Google's data interchange format
Copyright 2008 Google Inc.
https://developers.google.com/protocol-buffers/
This package contains a precompiled binary version of the protocol buffer
compiler (protoc). This binary is intended for users who want to use Protocol
Buffers in languages other than C++ but do not want to compile protoc
themselves. To install, simply place this binary somewhere in your PATH.
If you intend to use the included well known types then don't forget to
copy the contents of the 'include' directory somewhere as well, for example
into '/usr/local/include/'.
Please refer to our official github site for more installation instructions:
https://github.com/protocolbuffers/protobuf
提示我们,如果需要使用include目录中的内容,则我们需要把include目录也一同拷贝到和bin目录并列的位置,比如:
如上图是我本地的一个位置放置关系,默认的include目录中有一个google的目录,这样copy过来后,如果我们需要在proto文件中import google目录中的文件就可以直接写相对路径了,比如:
这里显示的是红色的,不影响编译,这是goland ide的问题,只要我们设置下ide就可以了。这里指定的位置就是我们上面安装的时候include放置的位置。设置成功后再看回到proto文件就是正常的了
编译生成go的pb文件需要插件,安装:
go get github.com/golang/protobuf/protoc-gen-go
如果我们用到了go-micro微服务框架,还需要安装
go get github.com/micro/micro/v2/cmd/protoc-gen-micro
二、Protobuf语法解析
标量类型 (Scalar Value Types)
proto类型 Go类型 备注
double float64
float float
int32 int32 编码负数值相对低效
int64 int64 编码负数值相对低效
uint32 uint32
uint64 uint64
sint32 int32 当值为负数时候,编码比int32更高效
sint64 int64 当值为负数时候,编码比int64更高效
fixed32 uint32 当值总是大于2^28时,编码比uint32更高效
fixed64 uint64 当值总是大于2^56时,编码比uint32更高效
sfixed32 int32
sfixed64 int64
bool bool
string string 只能是utf-8编码或者7-bit ASCII文本,且长度不得大于2^32
bytes []byte 不大于2^32的任意长度字节序列
message消息
// 普通的message
message SearchRequest {
string query = 1;
int32 page_number = 2;
int32 result_per_page = 3;
}
// 枚举 enum
enum Status {
STATUS_UNSPECIFIED = 0;
STATUS_OK = 1;
STATUS_FAIL= 2;
STATUS_UNKNOWN = -1; // 不推荐有负数
}
// 保留字段
message ReservedMessage {
reserved 2, 15, 9 to 11;
reserved "foo", "bar";
// string abc = 2; // 编译报错
// string foo = 3; // 编译报错
}
// 保留枚举
enum ReservedEnum {
reserved 2, 15, 9 to 11, 40 to max;
reserved "FOO", "BAR";
// FOO = 0; // 编译报错
F = 0;
}
// nested 嵌套message
message SearchResponse {
message Result {
string url = 1 ;
string title = 2;
}
enum Status {
UNSPECIFIED = 0;
OK = 1;
FAIL= 2;
}
Result results = 1;
Status status = 2;
}
// repeated
message RepeatedMessage {
repeated SearchRequest requests = 1;
repeated Status status = 2;
repeated int32 number = 3;
}
// map类型
message MapMessage{
map<string, string> message = 1;
map<string, SearchRequest> request = 2;
}
// any 类型
import "google/protobuf/any.proto";
message AnyMessage {
string message = 1;
google.protobuf.Any details = 2;
}