簡介
本文主要給大家介紹了關于go語言安裝使用protobuf的相關內容,分享出來供大家參考學習,下面話不多說了,來一起看看詳細的介紹吧。
protobuf是Google開發出來的一個語言無關、平臺無關的數據序列化工具,在rpc或tcp通信等很多場景都可以使用。通俗來講,如果客戶端和服務端使用的是不同的語言,那么在服務端定義一個數據結構,通過protobuf轉化為字節流,再傳送到客戶端解碼,就可以得到對應的數據結構。這就是protobuf神奇的地方。并且,它的通信效率極高,“一條消息數據,用protobuf序列化后的大小是json的10分之一,xml格式的20分之一,是二進制序列化的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
執行 protoc -h
查看安裝是否成功
安裝插件 protoc-gen-go,它是一個go程序,編譯它之后將可執行文件執行路徑寫入環境變量
go get github.com/golang/protobuf/protoc-gen-go
獲取proto包
go get github.com/golang/protobuf/proto
在go中使用
protobuf的使用方法是將數據結構寫入到.proto文件中,使用protoc編譯器編譯(間接使用了插件)得到一個新的go包,里面包含go中可以使用的數據結構和一些輔助方法。
編寫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;
}
}
編譯:
執行 protoc --go_out=. *.proto
生成 test.pb.go 文件
將test.pb.go文件放入example文件夾(對應上面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
}
一些對應關系
- message Test對為 struct 結構,其屬性字段有了對應的get方法,在go中可以使用
test.GetLabel()
、test.GetType()
獲取test對象的屬性
- OptionalGroup對應為 struct中的內嵌struct
- proto文件中repeated屬性對于slice結構
test.Reset()
可以使其所有屬性置為0值
- 使用Marshal和Unmarshal可以輕松的編碼和解碼
這些只是一些特性,想要仔細研究可以查看github上的wiki:https://github.com/golang/protobuf
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
您可能感興趣的文章:- 詳解vue中使用protobuf踩坑記
- vue中使用protobuf的過程記錄
- Android中使用protobuf的具體示例
- C#使用Protocol Buffer(ProtoBuf)進行Unity中的Socket通信
- Protobuf的簡要介紹及使用詳解