??在接入第三方數(shù)據(jù)流或接入物聯(lián)網(wǎng)設(shè)備時(shí),,通常這些數(shù)據(jù)所上報(bào)的數(shù)據(jù)只是按照指定的協(xié)議所編碼,,上報(bào)的數(shù)據(jù)流也不夠緊湊,如我們直接存儲這類字節(jié)流數(shù)據(jù)也比較大,。此時(shí)可以將字節(jié)流轉(zhuǎn)為其他壓縮格式的流,,如Protobuf等;
??將字節(jié)流轉(zhuǎn)為Protobuf流具體流程為:定義Proto文件,、生成對應(yīng)的Proto對象,、讀取流數(shù)據(jù)寫入Proto對象、序列化Proto對象,。
定義Proto文件:
syntax = "proto3";
//包名,,通過protoc生成時(shí)go文件
package data;
//位置
message position {
int32 type = 1;
int32 lon = 2;
int32 lat= 3;
string status = 4;
}
程序
??將字節(jié)數(shù)據(jù)轉(zhuǎn)為Protobuf所生成的對象;
數(shù)據(jù)流協(xié)議為7E頭7E尾,,簡單起見這里就不使用轉(zhuǎn)碼了,,字節(jié)格式如下。
?? 7E-類型-經(jīng)度-緯度-狀態(tài)長度-狀態(tài)
str := "7E0106C1FC5A0160C9640231327E"
buf := bytes.NewBuffer(toBytes(str))
p :=&test.Position{}
//跳過頭
buf.Next(1)
//讀取類型
var b byte
b,_=buf.ReadByte()
p.Type = int32(b)
//獲取經(jīng)度
lon:=[]byte{0,0,0,0}
buf.Read(lon)
p.Lon=bytesToInt(lon)
//獲取緯度
lat:=[]byte{0,0,0,0}
buf.Read(lat)
p.Lat=bytesToInt(lat)
//獲取狀態(tài)
len,_:=buf.ReadByte()
//獲取len個(gè)長度的字節(jié)數(shù)組
data:= buf.Next(int(len))
p.Status=string(data)
fmt.Println("對象輸出:",p.String())
fmt.Println("Protobuf序列化: ",hex.EncodeToString(pData))
fmt.Println("原始數(shù)據(jù):",str)
輸出結(jié)果:
??對象輸出: type:1 lon:113376346 lat:23120228 status:"12"
??Protobuf序列化: 080110daf8873618e492830b22023132
??原始數(shù)據(jù): 7E0106C1FC5A0160C9640231327E
??由于這個(gè)例子數(shù)據(jù)字段比較少,,并沒有看出Protobuf序列化的優(yōu)勢,,具體對比可看這篇文章:透過byte數(shù)組簡單分析Java序列化、Kryo、ProtoBuf序列化
|