ProtocolBuffers

ProtocolBuffers

windows下go安装并使用protobuf

结构化数据存储格式,性能和效率优于Json和Xml,是以二进制方式存储,占用空间小

Protobuf 在 .proto 定义需要处理的结构化数据,可以通过 protoc 工具,将 .proto 文件转换为 C、C++、Golang、Java、Python 等多种语言的代码,兼容性好,易于使用

安装

protoc

protoc下载地址, windows下载-win64结尾的那个

下载完后将protoc.exe放到%GOPATH%/bin目录下

protoc-gen-go

protoc本身不能将proto编译成go语言,需要安装插件

1
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest

下载完后可以在%GOPATH%/bin找到

1
2
3
# 检查是否安装成功
protoc --version
protoc-gen-go --version

使用

  1. 创建test.proto文件,.proto文件:用于定义需要传输的message格式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
syntax = "proto3"; //版本号
package protobuf; //包名
option go_package = "./protobuf"; // 生成在当前文件下的目录

enum ClassName{//枚举
class1 = 0; //标号 必须从 0开始
class2 = 1;
class3 = 2;
}

message Student{//消息,对应于Go的结构体
string name = 1; //1:标号,唯一 即可(相当于数据库中的Id,不一定要从1 ,2的顺序依次排列。)
int32 age = 2; //必须指定整型的范围,如int32,int64
string address = 3;
ClassName cn = 4;
}
message Students{
repeated Student person = 1; // repeated 修饰,相当于Go中切片
string school = 2;
}

  1. 命令protoc --go_out=. test.proto生成对应go文件,会看到生成/protobuf/student.pb.go文件

  2. 测试

    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
    func main() {
    student := &protobuf.Student{
    Name: "Huzhen",
    Age: 27,
    Address: "aaa",
    Cn: protobuf.ClassName_class1,
    }

    fmt.Println("student: ", student)
    // 编码: 将person对象进行序列化,得到二进制文件
    data, err := proto.Marshal(student)
    if err != nil {
    fmt.Println("encode err: ", err)
    return
    }

    fmt.Println("data: ", data)

    // 解码(反序列化)
    person2 := &protobuf.Student{}
    err = proto.Unmarshal(data, person2)
    if err != nil {
    fmt.Println("decode err: ", err)
    return
    }
    fmt.Println("person2: ", person2)
    }


ProtocolBuffers
http://xwww12.github.io/2023/11/16/go/ProtocolBuffers/
作者
xw
发布于
2023年11月16日
许可协议