Go语言与Prorobuf
Go语言与Protobuf
1. Protobuf 介绍
Protobuf 是 Protocol Buffers 的简称 ,是Google开源的的一种数据描述语言,其初始定位类似于 XML 和 json 等数据描述语言,Protobuf 最常见的使用场景是用于RPC系统中,这是因为protobuf 是一种轻便高效的结构化数据存储格式,可以序列化,比较适合做数据存储或者RPC数据交互格式
2. Protobuf 协议语法
我们注意到编写的 .proto
文件是按特定的语法格式编写的Protobuf的语法相对很简单
Protobuf的语目有proto2
和proto3
两个版本
如果项目无历史负担,强烈推荐使用 proto3 的语法编写 .proto
文件
3. Protobuf与RPC
我们将Protobuf 和RPC 结合起来做一个简单的Demo
步骤如下 :
- 编写
.proto
文件 - 自动生成代码
.pb.go
的代码文件 - 编写 RPC的服务端
- 编写 PRC的客户端
- 运行测试
编写 demo.proto
文件
syntax = "proto3"; // 使用 protobuf3的语法
package example;
message Demo3Request {
int64 id = 1;
}
message Demo3Response {
string name = 1;
int32 age = 2;
enum Gender {
MALE = 0;
FEMALE = 1;
UNKNOWN = 2;
}
message Other {
string addr = 1;
string hobby = 2;
Gender g = 3;
}
Other info = 3;
}