protocol buffers介绍

protocol buffers 介绍

什么是 protocol buffers

Protocol buffers 是谷歌开源的,与语言无关,平台无关,可扩展机制,数据结构序列化的语言,更小,更快,更简单,只需要定义一次结构,然后就可以生成多语言的数据结构对象
在这里插入图片描述

怎么使用

proto3的使用
golang如何使用proto

定义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 的结果

pb-vs-json

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

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值