概述
Google Protocol Buffer(简称 Protobuf)是一种轻平台无关,语言无关,可扩展的序列化结构数据格式。所以很适合用做数据存储和作为不同应用,不同语言之间相互通信的数据交换格式,只要实现相同的协议格式即同一proto文件被编译成不同的语言版本,加入到各自的工程中去。这样不同语言就可以解析其他语言通过 protobuf序列化的数据。
官方网站 https://github.com/protocolbuffers/protobuf
安装protoc
使用protobuf的需要首先安装protobuf编译器protoc,安装方式有很多种形式,如下
二进制文件
最方便快捷,下载地址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
mac os安装
$ brew install protobuf
$ protoc -h
安装protoc-gen-go
需要把pb 数据描述文件转换成go文件 ,需要使用pb 的go生成插件工具,Github下载地址: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插件
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
执行go install命令会在GOPATH/bin下生成protoc-gen-go可执行文件,一般将GOPATH/bin设置到系统的环境变量里
$ cd $GOPATH/bin
$ ls protoc-gen-go
或者
# Install proto3 from source
# brew install autoconf automake libtool
# git clone https://github.com/google/protobuf
# ./autogen.sh ; ./configure ; make ; make install
#
# Update protoc Go bindings via
# go get -u github.com/golang/protobuf/{proto,protoc-gen-go}
#
# See also
# https://github.com/grpc/grpc-go/tree/master/examples
Hello world
需要将数据结构写入到以.proto结尾的文件,创建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
测试文件
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}