protocol buffers 介绍
什么是 protocol buffers
Protocol buffers 是谷歌开源的,与语言无关,平台无关,可扩展机制,数据结构序列化的语言,更小,更快,更简单,只需要定义一次结构,然后就可以生成多语言的数据结构对象
怎么使用
定义pb
使用 protoc-gen-go 讲定义的 proto生成go的结构体
syntax = "proto3";
option go_package = "lib/proto/tmp";
package tmp;
message Test1 {
int32 id = 1;
}
message Test2 {
string b = 2;
}
性能测试
pb 和 json的 Marshal 和 Unmarshal 的结果
proto
syntax = "proto3";
option go_package = "lib/proto/model";
package model;
message User {
int64 id = 1;
string name = 2;
int64 age = 3;
string desc = 4;
}
测试代码
package pb_vs_json
import (
"d-grpc/lib/proto/model"
"encoding/json"
"github.com/golang/protobuf/proto"
"testing"
)
// go test -bench=. -benchmem
func BenchmarkJson(b *testing.B) {
user := &model.User{
Id: 1,
Name: "xph",
Age: 1,
Desc: "abcdefg",
}
var data []byte
b.ResetTimer()
for i := 0; i < b.N; i++ {
data, _ = json.Marshal(user)
_ = json.Unmarshal(data, user)
data = nil
}
}
func BenchmarkPB(b *testing.B) {
user := &model.User{
Id: 1,
Name: "xph",
Age: 1,
Desc: "abcdefg",
}
var data []byte
b.ResetTimer()
for i := 0; i < b.N; i++ {
data, _ = proto.Marshal(user)
_ = proto.Unmarshal(data, user)
data = nil
}
}
PB编码结构
编码结构体图
proto的 write type
PB varint 编码
示例讲解
message Test1 {
int32 id = 1;
}
varint的类型是 0 , id的值为 150 编码后的字节,
08 96 01 = [0000 1000 ],[1010 1100 ],[0000 0010]
08 = 08 >>>3 | 0 = 1 这个1 是字段编号 tag
96 01 = [1] 001 0110 [0] 000 0001 (首位的高字节1代码后面还有字节数据,0代表这是最后的一组字节数据了,所以1和0在解析的时候可以去掉)
→ 000 0001 ++ 001 0110 (交换是因为,varint采用小端对齐存储-低端字节存放在低位地址)
→ 10010110
→ 128 + 16 + 4 + 2 = 150
PB string 编码
示例讲解
message Test2 {
string b = 2;
}
bytes 的的编码 b的值为 “testing” 编码后的字节,12 07 74 65 73 74 69 6e 67
tag: 0x12 -> 2
length: 0x07 -> 7 代表value的长度是7
value:74 65 73 74 69 6e 67 (字节转为字符为,testing)