Golang是内存安全的带垃圾回收的强类型语言,那么必然不鼓励直接拿到一个地址随便进行类型强转的,虽然通过unsafe包也可以做到。并且,Golang的结构体是不能设置单字节对齐的,所以发送一个结构化的msg给另一个进程时一定要做序列化,接收端收到再做对应的反序列化。当然,也可以使用XML/Json来做通信格式,但是它们是字符串,编解码效率更低,而且也得需要库的支持。有没有一个更加简单高效的编解码方式呢?Protobuf就是一个。
Protocol Buffers (a.k.a., protobuf)) are Google’s language-neutral, platform-neutral, extensible mechanism for serializing structured data. Protobuf是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,或者说序列化。它很适合做数据存储或 RPC 数据交换格式。可用于通讯协议、数据存储等领域的语言无关、平台无关、可扩展的序列化结构数据格式。
Protobuf 可以像C语言定义结构体一样定义自己的数据结构,可以说是一种DSL语言了,然后使用其代码生成器(Protobuf向各目标语言编译的编译器)生成对应的代码来读写这个数据结构,很方便。
安装文档:https://github.com/golang/protobuf
语法说明:https://developers.google.com/protocol-buffers/docs/tutorials
上面谷歌文档访问不了可以看:译Protobuf3语言指南
这里有一篇比较老的原理介绍:https://www.ibm.com/developerworks/cn/linux/l-cn-gpb/
如何阅读protobuf源码?https://www.zhihu.com/question/66985015
Protobuf 大概分成两部分:compiler 和 runtime, compiler 的前端是手写的递归下降 parser , 后端是各个目标语言的代码生成器,前后端通过 descriptor 联系起来,非常清晰,也便于扩展。
Golang使用的protobuf一个小例子:
- 新建一个test目录放ptoto文件和自动生成的代码
syntax = "proto3";
package test;
enum Sex{
Male = 0;
Female = 1;
}
message Student{
int32 id = 1;
string name = 2;
Sex sex = 3;
}
- 用protoc命令生成对应go代码
[test]$ protoc --go_out=. testmsg.proto
- 使用proto包来编解码
package main
import (
"awesomeProject/test"
"fmt"
"github.com/golang/protobuf/proto"
)
func main() {
s := &test.Student{
Id: 1,
Name: "Mike",
Sex: test.Sex_Female,
}
fmt.Println(s) // id:1 name:"Mike" sex:Female
data, _ := proto.Marshal(s)
fmt.Println(data) // [8 1 18 4 77 105 107 101 24 1]
ss := new(test.Student)
err := proto.Unmarshal(data, ss)
if err == nil {
fmt.Println(ss) // id:1 name:"Mike" sex:Female
}
}
Protobuf使用还是十分方便的。