最近在学习中遇到了protobuf,哇喔竟然不知道,马上进行了学习,protobuf也是数据解析的方式,平时使用最多的是json和xml,那么好了,对比下他们的区别,并且附上protobuf的使用。
数据交互xml、json、protobuf格式比较
1、json: 一般的web项目中,最流行的主要还是json。因为浏览器对于json数据支持非常好,有很多内建的函数支持。
2、xml: 在webservice中应用最为广泛,但是相比于json,它的数据更加冗余,因为需要成对的闭合标签。json使用了键值对的方式,不仅压缩了一定的数据空间,同时也具有可读性。
3、protobuf:是后起之秀,是谷歌开源的一种数据格式,适合高性能,对响应速度有要求的数据传输场景。因为profobuf是二进制数据格式,需要编码和解码。数据本身不具有可读性。因此只能反序列化之后得到真正可读的数据。
相对于其它protobuf更具有优势
1:序列化后体积相比Json和XML很小,适合网络传输
2:支持跨平台多语言
3:消息格式升级和兼容性还不错
4:序列化反序列化速度很快,快于Json的处理速速
结论:
在一个需要大量的数据传输的场景中,如果数据量很大,那么选择protobuf可以明显的减少数据量,减少网络IO,从而减少网络传输所消耗的时间。
使用
WIN7 + Go1.9.2+protobuf3.5.1
1.首先定义一个用于测试的proto文件test.proto,内容如下:
syntax = "proto3";
package example;
message Test {string strTest = 1;double dTest = 2;
repeated int64 i64RepsTest= 3;
}
2.需要下载两个exe来生成对应的go文件
②使用go get github.com/golang/protobuf/protoc-gen-go下载生成go格式代码的插件(默认会下载到GOPATH/bin中,而GOPATH/bin默认是c:/Users/Administrator/go/bin),得到protoc-gen-go.exe
③将protoc.exe、protoc-gen-go.exe和test.proto拷贝到同一个文件夹中
④protoc.exe --go_out=. test.proto,生成对应的go代码文件test.pb.go
3.下面使用代码
①使用go get github.com/golang/protobuf/proto安装protobuf库
②将生成的test.pb.go拷贝到项目中(这里必须注意,因为使用了package example,所以必须在项目中新建example文件夹再拷贝进去)
③在项目中使用protobuf库,以及引入Test
import (
"github.com/golang/protobuf/proto"
"../example" //这里根据项目结构决定example的位置
)
④测试代码(在这里测试了中文字符串,double数据以及int64的数据)
marshalTest := &example.Test{
*proto.String("test_string中文test"),
*proto.Float64(2.34),
[]int64{123456789123, 4, 5}}
data, err := proto.Marshal(marshalTest)
if err != nil {
fmt.Println("proto.Marshal err : ", err)
}
unmarshalTest := &example.Test{}
err = proto.Unmarshal(data, unmarshalTest)
if err != nil {
fmt.Println("proto.Unmarshal err : ", err)
}
fmt.Println("strTest = ", unmarshalTest.GetStrTest())
fmt.Println("doubleTest = ", unmarshalTest.GetDTest())
for _, v := range unmarshalTest.GetI64RepsTest() {
fmt.Println("int64 reps = ", v)
}
输出的结果
以上。