ProtocolBuffers
ProtocolBuffers
结构化数据存储格式,性能和效率优于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 |
|
下载完后可以在%GOPATH%/bin
找到
1 |
|
使用
- 创建
test.proto
文件,.proto
文件:用于定义需要传输的message格式
1 |
|
命令
protoc --go_out=. test.proto
生成对应go文件,会看到生成/protobuf/student.pb.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
28func 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/