概述

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

安装protoc

使用protobuf的需要首先安装protobuf编译器protoc,安装方式有很多种形式,如下

二进制文件

最方便快捷,下载地址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

mac os安装

  1. $ brew install protobuf
  1. $ protoc -h

安装protoc-gen-go

需要把pb 数据描述文件转换成go文件 ,需要使用pb 的go生成插件工具,Github下载地址: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插件

  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

执行go install命令会在GOPATH/bin下生成protoc-gen-go可执行文件,一般将GOPATH/bin设置到系统的环境变量里

  1. $ cd $GOPATH/bin
  2. $ ls protoc-gen-go

或者

  1. # Install proto3 from source
  2. # brew install autoconf automake libtool
  3. # git clone https://github.com/google/protobuf
  4. # ./autogen.sh ; ./configure ; make ; make install
  5. #
  6. # Update protoc Go bindings via
  7. # go get -u github.com/golang/protobuf/{proto,protoc-gen-go}
  8. #
  9. # See also
  10. # https://github.com/grpc/grpc-go/tree/master/examples

Hello world

需要将数据结构写入到以.proto结尾的文件,创建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

测试文件

  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}

GoGo/protobuf

https://github.com/gogo/protobuf