企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] > [home protocol-buffers](https://developers.google.com/protocol-buffers) ## 简述 1. 一种数据交换格式 2. 相对字符传递可节省一半左右流量 ``` message Person { string name = 1; int32 id = 2; repeated string email = 3; } ``` 相当于把 `name `等 `key` 换为数字进行传输 3. 他既可以用作client/server 之间的数据交互,也可以用作 rpc 即可 grpc 4. protobuf 会有粘包问题,解决办法是在转为字节后,再添加到字节头部 ``` // 一个 golang 的例子 func main() { msg := &protogo.Msg{To: "hello", From: "word"} // 序列化为 bytes byt, _ := proto.Marshal(msg) //把字节长度转为字节放入头部 b :=IntToBytes(len(byt)) byt =append(b,byt...) log.Printf("len %v , content %v",len(a),a) // len 19 , content [0 17 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1] } func IntToBytes(n int) []byte { x := uint16(n)//定义包头长度为 2 个字节 bytesBuffer := bytes.NewBuffer([]byte{}) binary.Write(bytesBuffer, binary.BigEndian, x) return bytesBuffer.Bytes() } ```