Google Protocol Buffer(简称 Protobuf)是一种轻平台无关,语言无关,可扩展的序列化结构数据格式。所以很适合用做数据存储和作为不同应用,不同语言之间相互通信的数据交换格式,只要实现相同的协议格式即同一proto文件被编译成不同的语言版本,加入到各自的工程中去。这样不同语言就可以解析其他语言通过 protobuf序列化的数据。
官方网站 https://github.com/protocolbuffers/protobuf

安装

二进制文件

最方便快捷,下载地址https://github.com/protocolbuffers/protobuf/releases
图片.png
根据protoc-版本号-系统平台.zip选择下载和解压文件,在解压的bin目录下执行

  1. sudo mv protoc /usr/bin

源代码编译安装

C++编译环境安装On Ubuntu/Debian, you can install them with:

  1. $ sudo apt-get install autoconf automake libtool curl make g++ unzip

  1. wget https://github.com/google/protobuf/releases/download/v3.5.1/protobuf-all-3.5.1.zip
  2. unzip protobuf-all-3.5.1.zip
  3. cd protobuf-3.5.1/
  4. ./configure
  5. make
  6. make install

mac os安装

  1. $ brew install protobuf
  2. $ protoc --version
  3. libprotoc 3.13.0

查看帮助文档

  1. $ protoc -h

Hello world

Golang

官方网站https://github.com/golang/protobuf
安装protoc-gen-go插件,会根据proto 文件转换成go 文件

  1. go get -d -u github.com/golang/protobuf/protoc-gen-go
  2. cd $GOPATH/src/github.com/golang/protobuf/protoc-gen-go
  3. go install

如果下载出现问题采用git,安装protoc-gen-go插件eg:

  1. mkdir -p $GOPATH/src/github.com/golang
  2. cd $GOPATH/src/github.com/golang
  3. git clone https://github.com/golang/protobuf.git
  4. cd protobuf/protoc-gen-go
  5. go install

下载指定版本

  1. GIT_TAG="v1.3.5" # change as needed
  2. go get -d -u github.com/golang/protobuf/protoc-gen-go
  3. git -C "$(go env GOPATH)"/src/github.com/golang/protobuf checkout $GIT_TAG
  4. go install github.com/golang/protobuf/protoc-gen-go

创建student.proto

  1. syntax= 'proto3';
  2. package student;
  3. message Student{
  4. string name = 1;
  5. int32 age = 2;
  6. repeated string courses = 3;
  7. string remark = 4;
  8. }

编译文件生成,会生成student.pb.go

  1. protoc --go_out=./ *.proto

测试文件
安装proto go API

  1. go get -v -u github.com/golang/protobuf/proto
  1. package main
  2. import (
  3. "cn.baxiang/protocbuf"
  4. "fmt"
  5. "github.com/golang/protobuf/proto"
  6. )
  7. func main() {
  8. stu := &student.Student{Name:"tony",Age:20,Courses:[]string{"computer","math"},Remark:"stu"}
  9. // 编码
  10. bytes, e := proto.Marshal(stu)
  11. if e!= nil {
  12. fmt.Println(e.Error())
  13. }
  14. s := student.Student{}
  15. proto.Unmarshal(bytes,&s)
  16. fmt.Println(s)
  17. }

执行结果

  1. {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