您好,登錄后才能下訂單哦!
簡(jiǎn)介
本文主要給大家介紹了關(guān)于go語(yǔ)言安裝使用protobuf的相關(guān)內(nèi)容,分享出來(lái)供大家參考學(xué)習(xí),下面話(huà)不多說(shuō)了,來(lái)一起看看詳細(xì)的介紹吧。
protobuf是Google開(kāi)發(fā)出來(lái)的一個(gè)語(yǔ)言無(wú)關(guān)、平臺(tái)無(wú)關(guān)的數(shù)據(jù)序列化工具,在rpc或tcp通信等很多場(chǎng)景都可以使用。通俗來(lái)講,如果客戶(hù)端和服務(wù)端使用的是不同的語(yǔ)言,那么在服務(wù)端定義一個(gè)數(shù)據(jù)結(jié)構(gòu),通過(guò)protobuf轉(zhuǎn)化為字節(jié)流,再傳送到客戶(hù)端解碼,就可以得到對(duì)應(yīng)的數(shù)據(jù)結(jié)構(gòu)。這就是protobuf神奇的地方。并且,它的通信效率極高,“一條消息數(shù)據(jù),用protobuf序列化后的大小是json的10分之一,xml格式的20分之一,是二進(jìn)制序列化的10分之一”。
安裝
編譯安裝protobuf的編譯器protoc
wget https://github.com/google/protobuf/releases/download/v2.6.1/protobuf-2.6.1.tar.gz tar zxvf protobuf-2.6.1.tar.gz cd protobuf-2.6.1./configure make make install
執(zhí)行 protoc -h
查看安裝是否成功
安裝插件 protoc-gen-go,它是一個(gè)go程序,編譯它之后將可執(zhí)行文件執(zhí)行路徑寫(xiě)入環(huán)境變量
go get github.com/golang/protobuf/protoc-gen-go
獲取proto包
go get github.com/golang/protobuf/proto
在go中使用
protobuf的使用方法是將數(shù)據(jù)結(jié)構(gòu)寫(xiě)入到.proto文件中,使用protoc編譯器編譯(間接使用了插件)得到一個(gè)新的go包,里面包含go中可以使用的數(shù)據(jù)結(jié)構(gòu)和一些輔助方法。
編寫(xiě)test.proto文件
package example; enum FOO { X = 17; }; message Test { required string label = 1; optional int32 type = 2 [default=77]; repeated int64 reps = 3; optional group OptionalGroup = 4 { required string RequiredField = 5; } }
編譯:
執(zhí)行 protoc --go_out=. *.proto
生成 test.pb.go 文件
將test.pb.go文件放入example文件夾(對(duì)應(yīng)上面package)中,作為example包
try
package main import ( "log" "github.com/golang/protobuf/proto" "example" ) func main() { test := &example.Test { Label: proto.String("hello"), Type: proto.Int32(17), Reps: []int64{1, 2, 3}, Optionalgroup: &example.Test_OptionalGroup { RequiredField: proto.String("good bye"), }, } data, err := proto.Marshal(test) if err != nil { log.Fatal("marshaling error: ", err) } newTest := &example.Test{} err = proto.Unmarshal(data, newTest) if err != nil { log.Fatal("unmarshaling error: ", err) } // Now test and newTest contain the same data. if test.GetLabel() != newTest.GetLabel() { log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) } //test.GetOptionalgroup().GetRequiredField() //etc }
一些對(duì)應(yīng)關(guān)系
test.GetLabel()
、test.GetType()
獲取test對(duì)象的屬性test.Reset()
可以使其所有屬性置為0值這些只是一些特性,想要仔細(xì)研究可以查看github上的wiki:https://github.com/golang/protobuf
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。