Protobuf簡(jiǎn)介
? ? ? ? Protocol Buffer是一種輕便的、高效的結(jié)構(gòu)化數(shù)據(jù)存儲(chǔ)格式,相比于JSON、XML等其他結(jié)構(gòu)化數(shù)據(jù)格式性能和效率大幅提升,Protobuf以二進(jìn)制存儲(chǔ)、占用空間小。Protobuf在通信協(xié)議和數(shù)據(jù)存儲(chǔ)等領(lǐng)域應(yīng)用廣泛。
? ? Protobuf在 .proto 中定義結(jié)構(gòu)化數(shù)據(jù),可以通過(guò)protoc工具講 .proto文件轉(zhuǎn)化為C、Java、Golang等多種語(yǔ)言的代碼,兼容性好,易于使用
Protobuf安裝
可以到github上搜索protobuf,第一個(gè)就是,這里也給出鏈接https://github.com/protocolbuffers/protobuf

我們還要下載Go語(yǔ)言對(duì)應(yīng)的工具,這個(gè)工具就是上文提到的protoc,再開(kāi)一眼不要嫌麻煩??https://github.com/protocolbuffers/protobuf-go
Protobuf在?.proto?中定義結(jié)構(gòu)化數(shù)據(jù),可以通過(guò)protoc工具講?.proto文件轉(zhuǎn)化為C、Java、Golang等多種語(yǔ)言的代碼,兼容性好,易于使用
Protobuf文件內(nèi)容
?消息類型(消息名采用首字母大寫(xiě)駝峰風(fēng)格)
?說(shuō)了這么多,我們來(lái)看看 .proto 文件的是一個(gè)入門(mén)實(shí)例
//protobuf有兩個(gè)版本,默認(rèn)是proto2,如果需要proto3需要顯示指定
syntax =? “proto3”;
//定義包名
package main;
//message是關(guān)鍵字,又來(lái)指定消息類型,這里的消息類型會(huì)轉(zhuǎn)換為Go語(yǔ)言中的結(jié)構(gòu)體,我們可以看到字段被賦值,這并不是真正意義上的賦值,我們叫它數(shù)字標(biāo)識(shí)符,每個(gè)字段有唯一的數(shù)字標(biāo)識(shí)符,范圍是 1~2^29-1
message Student {
? ? ? ? string? name = 1;
? ? ? ? bool? male = 2;
? ? ? ? repeated? int32 scores = 3;
}
字段類型(字段名使用小寫(xiě)下劃線風(fēng)格)
?標(biāo)量類型(Scalar)
以下是常見(jiàn)的,具體可以去Protobuf官網(wǎng)查看(https://developers.google.cn/protocol-buffers/)
浮點(diǎn)型:double、float
數(shù)字型:int32、int64、uint32、uint64
布爾型:bool
字符型:string
字節(jié)數(shù)組:bytes相當(dāng)于Go語(yǔ)言的[]byte
?枚舉(Enumerations)
我們通常使用關(guān)鍵字 enum定義枚舉類型
enum MonthEnum {
? ? JANUARY = 0;
? ? FEBRUARY = 1;
? ? ?.....
}
?消息類型間的嵌套
message Person {
????????repeated? ?Student? student = 1;
}
message Student {
????????string name = 1;
????????string gender = 2;
????????repeated string score = 3;
}
?oneof(作用類似c里的聯(lián)合體,寫(xiě)配置文件類似)
message Person {
? ? ? int32? height = 1;
??????oneof {
? ??????????string name = 2;?
? ???????????int32? age = 3;
? ? ? }
}
?map
message Maps {
????????map<string, string>? ?id_name? ?= 1;
}
服務(wù)(RPC服務(wù)名和方法名,均采用首字母大寫(xiě)駝峰風(fēng)格,但不強(qiáng)制哦)?
如果消息類型用于遠(yuǎn)程通信RPC,我們可以在.proto文件中定義RPC服務(wù)接口,關(guān)鍵字為 service
/*使用service關(guān)鍵字定義一個(gè)Keep服務(wù),服務(wù)的參數(shù)KeepRequest,返回值KeepResponse*/
service KeepService {
? ? ? ? rpc? Keep (KeepRequest) returns? (KeepResponse);
}
? ? 在Go語(yǔ)言中我們可以使用,protoc工具講proto文件轉(zhuǎn)化為對(duì)應(yīng)的 .go文件
protoc? --go_out=.? ?*.proto? ?//注意:要在protoc文件所在目錄下執(zhí)行該命令
如果出現(xiàn)一下問(wèn)題應(yīng)在 .proto文件中加入如下(option go_backage="./;pb";)

