Google Protocol Buffer(简称 Protobuf)是一种轻平台无关,语言无关,可扩展的序列化结构数据格式。所以很适合用做数据存储和作为不同应用,不同语言之间相互通信的数据交换格式,只要实现相同的协议格式即同一proto文件被编译成不同的语言版本,加入到各自的工程中去。这样不同语言就可以解析其他语言通过 protobuf序列化的数据。
官方网站 https://github.com/protocolbuffers/protobuf
安装
二进制文件
最方便快捷,下载地址https://github.com/protocolbuffers/protobuf/releases
根据protoc-版本号-系统平台.zip选择下载和解压文件,在解压的bin目录下执行
sudo mv protoc /usr/bin
源代码编译安装
C++编译环境安装On Ubuntu/Debian, you can install them with:
$ sudo apt-get install autoconf automake libtool curl make g++ unzip
wget https://github.com/google/protobuf/releases/download/v3.5.1/protobuf-all-3.5.1.zip
unzip protobuf-all-3.5.1.zip
cd protobuf-3.5.1/
./configure
make
make install
mac os安装
$ brew install protobuf
$ protoc --version
libprotoc 3.13.0
查看帮助文档
$ protoc -h
Hello world
Golang
官方网站https://github.com/golang/protobuf
安装protoc-gen-go插件,会根据proto 文件转换成go 文件
go get -d -u github.com/golang/protobuf/protoc-gen-go
cd $GOPATH/src/github.com/golang/protobuf/protoc-gen-go
go install
如果下载出现问题采用git,安装protoc-gen-go插件eg:
mkdir -p $GOPATH/src/github.com/golang
cd $GOPATH/src/github.com/golang
git clone https://github.com/golang/protobuf.git
cd protobuf/protoc-gen-go
go install
下载指定版本
GIT_TAG="v1.3.5" # change as needed
go get -d -u github.com/golang/protobuf/protoc-gen-go
git -C "$(go env GOPATH)"/src/github.com/golang/protobuf checkout $GIT_TAG
go install github.com/golang/protobuf/protoc-gen-go
创建student.proto
syntax= 'proto3';
package student;
message Student{
string name = 1;
int32 age = 2;
repeated string courses = 3;
string remark = 4;
}
编译文件生成,会生成student.pb.go
protoc --go_out=./ *.proto
测试文件
安装proto go API
go get -v -u github.com/golang/protobuf/proto
package main
import (
"cn.baxiang/protocbuf"
"fmt"
"github.com/golang/protobuf/proto"
)
func main() {
stu := &student.Student{Name:"tony",Age:20,Courses:[]string{"computer","math"},Remark:"stu"}
// 编码
bytes, e := proto.Marshal(stu)
if e!= nil {
fmt.Println(e.Error())
}
s := student.Student{}
proto.Unmarshal(bytes,&s)
fmt.Println(s)
}
执行结果
{tony 20 [computer math] stu {} [] 0}
参考
https://developers.google.com/protocol-buffers/docs/proto
https://colobu.com/2017/03/16/Protobuf3-language-guide/
https://zhuanlan.zhihu.com/p/63633965
https://blog.csdn.net/carson_ho/article/details/70267574