1. 程式人生 > >ProtoBuf安裝及使用

ProtoBuf安裝及使用

ProtoBuf: 是一套完整的 IDL(介面描述語言),出自Google,基於 C 進行的實現,開發人員可以根據 ProtoBuf 的語言規範生成多種程式語言(Golang、Python、Java 等)的介面程式碼,本篇只講述 Golang 的基礎操作。據說 ProtoBuf 所生成的二進位制檔案在儲存效率上比 XML 高 3~10 倍,並且處理效能高 1~2 個數量級,這也是選擇 ProtoBuf 作為序列化方案的一個重要因素之一。

安裝

1、安裝 protoc :protoc下載地址,可以根據自己的系統下載相應的 protoc,推薦下載編譯好的二進位制檔案包壓縮包;

2、配置 protoc 到系統的環境變數中,執行如下命令檢視是否安裝成功:

1 $protoc--version

3、安裝 ProtoBuf 相關的 golang 依賴庫

1 $goget-ugithub.com/golang/protobuf/
{protoc-gen-go,proto}

使用

1、建立 Demo golang工程

2、在 example 包中編寫 person.proto
1234567891011 syntax="proto3";packageexample;messageperson{//aa會生成Aa命名的結構體int32id=1;stringname=2;}messageall_person{//aa_bb會生成AaBb的駝峰命名的結構體repeatedpersonPer=1;}

3、進入 Demo 工程的 example 目錄,使用 protoc 編譯 person.proto

1 $protoc--go_out=.person.proto

就會生成 person.pb.go 檔案

4、在 golang 工程中使用 protobuf 進行序列化與反序列化

123456789101112131415161718192021222324252627282930313233343536373839 packagemainimport("github.com/golang/protobuf/proto""Demo/example""log")funcmain(){// 為 AllPerson 填充資料p1:=example.Person{Id:*proto.Int32(1),Name:*proto.String("xieyanke"),}p2:=example.Person{Id:2,Name:"gopher",}all_p:=example.AllPerson{Per:[]*example.Person{&p1,&p2},}// 對資料進行序列化data,err:=proto.Marshal(&all_p)iferr!=nil{log.Fatalln("Mashal data error:",err)}// 對已經序列化的資料進行反序列化vartarget example.AllPersonerr=proto.Unmarshal(data,&target)iferr!=nil{log.Fatalln("UnMashal data error:",err)}println(target.Per[0].Name)// 列印第一個 person Name 的值進行反序列化驗證}
 參考連結: