Buf 博客 Protobuf Tip 系列全译:10 条 Protobuf 实用技巧【译】

本文汇总翻译自 Buf 官方博客的 Protobuf Tip 系列文章(共 10 篇)。该系列由 Buf 团队撰写,Tip #1–#9 的作者是 M. C. Sunny Young de la Sota,Tip #10 的作者是 Kevin McDonald。每节开头附有原文链接。系列文章中的插图由 D2 图表语言生成,本文直接引用原文 SVG 链接。 系列概览 # 标题 一句话总结 原文 1 字段名是永恒的 永远不要重命名字段 链接 2 压缩你的 Protos! 压缩无处不在,编码体积的权衡没那么重要 链接 3 枚举名需要前缀 枚举值的 FQN 不含枚举名,必须加前缀避免冲突 链接 4 接受我们无法修复的错误 分布式场景下有些错误不值得修,不破坏用户更重要 链接 5 避免 import public/weak 这两个特性是 C++ 历史包袱,不要用 链接 6 枚举别名的隐性危险 allow_alias 会坑到反射和 JSON,别用 链接 7 看清二进制的工具 buf convert + protoscope 调试 wire format 链接 8 永远不要用 required required 是 proto2 的大坑,无法安全移除 链接 9 有些数字比其他数字更"平等" 字段编号 1–15 解码最快 链接 10 选择正确的整数类型 默认用 int64 就对了 链接 Tip #1:字段名是永恒的 原文:Protobuf Tip #1: Field names are forever (2025-04-08) ...

2026-09-15 · 13 分钟 · DimAgent

在rust中使用protobuf

常规方式 安装必要工具 # 安装 protoc # 在 macOS 上: brew install protobuf # 在 Ubuntu 上: sudo apt-get install protobuf-compiler # 安装 Rust protobuf 代码生成器 cargo install protobuf-codegen 示例 创建一个protobuf的文件: message.proto syntax = "proto3"; package mypackage; message Person { string name = 1; int32 age = 2; string email = 3; } 然后执行命令 protoc --rust_out=. message.proto 如果是在项目中,在你的 Rust 项目中,添加必要的依赖到 Cargo.toml: [dependencies] protobuf = "2.27.1" 然后可以在代码中访问生成的内容 use protobuf::Message; mod message; // 引入生成的模块 use message::Person; fn main() { let mut person = Person::new(); person.set_name("Alice".to_string()); person.set_age(30); person.set_email("alice@example.com".to_string()); // 序列化 let encoded: Vec<u8> = person.write_to_bytes().unwrap(); // 反序列化 let decoded = Person::parse_from_bytes(&encoded).unwrap(); println!("Name: {}", decoded.get_name()); println!("Age: {}", decoded.get_age()); println!("Email: {}", decoded.get_email()); } 可以借助build.rs来自动化这一步骤: ...

2024-08-29 · 2 分钟 · czyt

Buf使用备忘

Buf 工具针对于Schema驱动、基于 Protobuf 的 API 开发,为服务发布者和服务客户端提供可靠和更好的用户体验。简化了您的 Protobuf 管理策略,以便您可以专注于重要的事情。 下载安装 可以直接去buf的GitHub的release 页面下载,其他的安装方式参考官方文档 使用 三个yaml文件 初次接触buf项目的时候,有个疑问就是buf项目中buf.yaml buf.gen.yaml buf.work.yaml这个三个文件的区别和用途。下面是简单的一个表,列出了三个文件的区别: 文件名 文件位置 说明 buf.yaml 每个proto模块定义的根目录 buf.yaml 配置的位置告诉 buf 在哪里搜索 .proto 文件,模块的依赖项以及如何处理导入 buf.gen.yaml 一般放在仓库的根目录 文件控制 buf generate 命令如何针对任何输入执行 protoc 插件 buf.work.yaml 一般放在仓库的根目录 定义项目需要哪些proto模块 示例目录结构: . ├── buf.gen.yaml ├── buf.work.yaml ├── proto │ ├── acme │ │ └── weather │ │ └── v1 │ │ └── weather.proto │ └── buf.yaml └── vendor └── protoc-gen-validate ├── buf.yaml └── validate └── validate.proto 一个buf.yaml 的样例,可以通过buf mod init来创建: ...

2023-07-29 · 2 分钟 · czyt

使用protoc-gen-star编写protoc插件

预备知识 需要安装的软件 protoc golang go 软件包 github.com/lyft/protoc-gen-star 插件调用步骤 protoc,PB编译器,使用一组标志(记录在protoc -h下)进行配置,并将一组文件作为参数交给它。在这种情况下,I标志可以被多次指定,是它在proto文件中用于导入依赖关系的查找路径。默认情况下,官方描述符protos已经被包含在内。 myplugin_out 告诉 protoc 使用 protoc-gen-myplugin protoc-plugin。这些插件会从系统的 PATH 环境变量中自动解析,或者可以用另一个标志明确指定。官方的protoc-plugins (例如,protoc-gen-python) 已经在protoc注册了。该标志的值是特定于特定插件的,但 :…/generated 后缀除外。这个后缀表示protoc将把该包生成的文件放在哪个根目录下(相对于当前工作目录)。然而,这个生成的输出目录不会传播给 protoc-gen-myplugin,所以它需要在标志的左边重复。PG* 通过一个 output_path 参数支持这一点。 protoc 解析传入的 proto 文件,确保它们在语法上是正确的,并加载任何导入的依赖项。它将这些文件和依赖关系转换成描述符 (它们本身就是 PB 消息),并创建一个 CodeGeneratorRequest (又是一个 PB)。protoc 将这个请求序列化,然后执行每个配置的 protoc-plugin,通过 stdin 发送有效载荷。 protoc-gen-myplugin 启动,接收请求的有效载荷,并将其解密。一个基于 PG* 的 protoc-plugin 有两个阶段。首先,PG* 对从 protoc 收到的 CodeGeneratorRequest 进行解密,并为每个文件和其包含的所有实体创建一个完全连接的抽象语法树 (AST)。为这个插件指定的任何参数也会被解析,以便以后使用。 当这一步完成后,PG*就会执行任何注册的模块,把构建的AST交给它。模块可以被写成生成人工制品(例如,文件),或者只是对所提供的图进行某种形式的验证而没有任何其他副作用。模块在针对PB的操作方面提供了极大的灵活性。 一旦所有的模块都被运行,PG*会将任何自定义的工件写入文件系统,或者将生成器特定的工件序列化为CodeGeneratorResponse并将数据发送到其stdout。这整个流程看起来像这样。 foo.proto → protoc → CodeGeneratorRequest → protoc-gen-myplugin → CodeGeneratorResponse → protoc → foo.pb.go 假设插件名称为diy,则需要编译程序为protoc-gen-diy,并将程序加入系统Path变量,通过下面的命令调用插件。 protoc -I . --diy_out=./gen/ xxxx.proto 使用protoc-gen-star包 模块 Modules PG*模块将被交付一个完整的AST,用于生成目标文件以及所有依赖项。然后,模块可以将文件添加到协议CodeGeneratorResponse或将文件作为组件直接写入磁盘。 ...

2022-10-29 · 3 分钟 · czyt

Protobuf golang小札

Oneof 如果您有许多字段的消息,并且最多可以同时设置一个字段,则可以使用Oneof功能来执行此行为并保存内存。一个字段就像常规字段一样,除了单一共享内存中的所有字段,最多可以同时设置一个字段。设置Oneof的任何成员都会自动清除所有其他成员。 ​ Google protobuf 文档#Oneof 示例proto 创建protoOneof.proto 的proto文件 syntax = "proto3"; package oneof_test; option go_package ='.;oneof'; message WeiboUser{ string user_id = 1; string user_nick = 2; } message DouyinUser{ string auth_token = 1; string nick_name = 2; } message User{ oneof user_source{ string weibo_url = 1; string douyin_url = 2; } oneof user_info{ WeiboUser weibo_user_info = 3; DouyinUser douyin_user_info = 4; } } 使用命令生成go代码 protoc --proto_path=. --go_out=paths=source_relative:./oneof ./protoOneof.proto 生成的protoOneof.pb.go代码如下: // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.28.0 // protoc v3.21.3 // source: protoOneof.proto package oneof import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type WeiboUser struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` UserNick string `protobuf:"bytes,2,opt,name=user_nick,json=userNick,proto3" json:"user_nick,omitempty"` } func (x *WeiboUser) Reset() { *x = WeiboUser{} if protoimpl.UnsafeEnabled { mi := &file_protoOneof_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *WeiboUser) String() string { return protoimpl.X.MessageStringOf(x) } func (*WeiboUser) ProtoMessage() {} func (x *WeiboUser) ProtoReflect() protoreflect.Message { mi := &file_protoOneof_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use WeiboUser.ProtoReflect.Descriptor instead. func (*WeiboUser) Descriptor() ([]byte, []int) { return file_protoOneof_proto_rawDescGZIP(), []int{0} } func (x *WeiboUser) GetUserId() string { if x != nil { return x.UserId } return "" } func (x *WeiboUser) GetUserNick() string { if x != nil { return x.UserNick } return "" } type DouyinUser struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields AuthToken string `protobuf:"bytes,1,opt,name=auth_token,json=authToken,proto3" json:"auth_token,omitempty"` NickName string `protobuf:"bytes,2,opt,name=nick_name,json=nickName,proto3" json:"nick_name,omitempty"` } func (x *DouyinUser) Reset() { *x = DouyinUser{} if protoimpl.UnsafeEnabled { mi := &file_protoOneof_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *DouyinUser) String() string { return protoimpl.X.MessageStringOf(x) } func (*DouyinUser) ProtoMessage() {} func (x *DouyinUser) ProtoReflect() protoreflect.Message { mi := &file_protoOneof_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use DouyinUser.ProtoReflect.Descriptor instead. func (*DouyinUser) Descriptor() ([]byte, []int) { return file_protoOneof_proto_rawDescGZIP(), []int{1} } func (x *DouyinUser) GetAuthToken() string { if x != nil { return x.AuthToken } return "" } func (x *DouyinUser) GetNickName() string { if x != nil { return x.NickName } return "" } type User struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Types that are assignable to UserSource: // *User_WeiboUrl // *User_DouyinUrl UserSource isUser_UserSource `protobuf_oneof:"user_source"` // Types that are assignable to UserInfo: // *User_WeiboUserInfo // *User_DouyinUserInfo UserInfo isUser_UserInfo `protobuf_oneof:"user_info"` } func (x *User) Reset() { *x = User{} if protoimpl.UnsafeEnabled { mi := &file_protoOneof_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *User) String() string { return protoimpl.X.MessageStringOf(x) } func (*User) ProtoMessage() {} func (x *User) ProtoReflect() protoreflect.Message { mi := &file_protoOneof_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use User.ProtoReflect.Descriptor instead. func (*User) Descriptor() ([]byte, []int) { return file_protoOneof_proto_rawDescGZIP(), []int{2} } func (m *User) GetUserSource() isUser_UserSource { if m != nil { return m.UserSource } return nil } func (x *User) GetWeiboUrl() string { if x, ok := x.GetUserSource().(*User_WeiboUrl); ok { return x.WeiboUrl } return "" } func (x *User) GetDouyinUrl() string { if x, ok := x.GetUserSource().(*User_DouyinUrl); ok { return x.DouyinUrl } return "" } func (m *User) GetUserInfo() isUser_UserInfo { if m != nil { return m.UserInfo } return nil } func (x *User) GetWeiboUserInfo() *WeiboUser { if x, ok := x.GetUserInfo().(*User_WeiboUserInfo); ok { return x.WeiboUserInfo } return nil } func (x *User) GetDouyinUserInfo() *DouyinUser { if x, ok := x.GetUserInfo().(*User_DouyinUserInfo); ok { return x.DouyinUserInfo } return nil } type isUser_UserSource interface { isUser_UserSource() } type User_WeiboUrl struct { WeiboUrl string `protobuf:"bytes,1,opt,name=weibo_url,json=weiboUrl,proto3,oneof"` } type User_DouyinUrl struct { DouyinUrl string `protobuf:"bytes,2,opt,name=douyin_url,json=douyinUrl,proto3,oneof"` } func (*User_WeiboUrl) isUser_UserSource() {} func (*User_DouyinUrl) isUser_UserSource() {} type isUser_UserInfo interface { isUser_UserInfo() } type User_WeiboUserInfo struct { WeiboUserInfo *WeiboUser `protobuf:"bytes,3,opt,name=weibo_user_info,json=weiboUserInfo,proto3,oneof"` } type User_DouyinUserInfo struct { DouyinUserInfo *DouyinUser `protobuf:"bytes,4,opt,name=douyin_user_info,json=douyinUserInfo,proto3,oneof"` } func (*User_WeiboUserInfo) isUser_UserInfo() {} func (*User_DouyinUserInfo) isUser_UserInfo() {} var File_protoOneof_proto protoreflect.FileDescriptor var file_protoOneof_proto_rawDesc = []byte{ 0x0a, 0x10, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x4f, 0x6e, 0x65, 0x6f, 0x66, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0a, 0x6f, 0x6e, 0x65, 0x6f, 0x66, 0x5f, 0x74, 0x65, 0x73, 0x74, 0x22, 0x41, 0x0a, 0x09, 0x57, 0x65, 0x69, 0x62, 0x6f, 0x55, 0x73, 0x65, 0x72, 0x12, 0x17, 0x0a, 0x07, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x75, 0x73, 0x65, 0x72, 0x49, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x6e, 0x69, 0x63, 0x6b, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x75, 0x73, 0x65, 0x72, 0x4e, 0x69, 0x63, 0x6b, 0x22, 0x48, 0x0a, 0x0a, 0x44, 0x6f, 0x75, 0x79, 0x69, 0x6e, 0x55, 0x73, 0x65, 0x72, 0x12, 0x1d, 0x0a, 0x0a, 0x61, 0x75, 0x74, 0x68, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x61, 0x75, 0x74, 0x68, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x69, 0x63, 0x6b, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x6e, 0x69, 0x63, 0x6b, 0x4e, 0x61, 0x6d, 0x65, 0x22, 0xe7, 0x01, 0x0a, 0x04, 0x55, 0x73, 0x65, 0x72, 0x12, 0x1d, 0x0a, 0x09, 0x77, 0x65, 0x69, 0x62, 0x6f, 0x5f, 0x75, 0x72, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x08, 0x77, 0x65, 0x69, 0x62, 0x6f, 0x55, 0x72, 0x6c, 0x12, 0x1f, 0x0a, 0x0a, 0x64, 0x6f, 0x75, 0x79, 0x69, 0x6e, 0x5f, 0x75, 0x72, 0x6c, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x09, 0x64, 0x6f, 0x75, 0x79, 0x69, 0x6e, 0x55, 0x72, 0x6c, 0x12, 0x3f, 0x0a, 0x0f, 0x77, 0x65, 0x69, 0x62, 0x6f, 0x5f, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x6f, 0x6e, 0x65, 0x6f, 0x66, 0x5f, 0x74, 0x65, 0x73, 0x74, 0x2e, 0x57, 0x65, 0x69, 0x62, 0x6f, 0x55, 0x73, 0x65, 0x72, 0x48, 0x01, 0x52, 0x0d, 0x77, 0x65, 0x69, 0x62, 0x6f, 0x55, 0x73, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x42, 0x0a, 0x10, 0x64, 0x6f, 0x75, 0x79, 0x69, 0x6e, 0x5f, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x6f, 0x6e, 0x65, 0x6f, 0x66, 0x5f, 0x74, 0x65, 0x73, 0x74, 0x2e, 0x44, 0x6f, 0x75, 0x79, 0x69, 0x6e, 0x55, 0x73, 0x65, 0x72, 0x48, 0x01, 0x52, 0x0e, 0x64, 0x6f, 0x75, 0x79, 0x69, 0x6e, 0x55, 0x73, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x42, 0x0d, 0x0a, 0x0b, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x42, 0x0b, 0x0a, 0x09, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x42, 0x09, 0x5a, 0x07, 0x2e, 0x3b, 0x6f, 0x6e, 0x65, 0x6f, 0x66, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protoOneof_proto_rawDescOnce sync.Once file_protoOneof_proto_rawDescData = file_protoOneof_proto_rawDesc ) func file_protoOneof_proto_rawDescGZIP() []byte { file_protoOneof_proto_rawDescOnce.Do(func() { file_protoOneof_proto_rawDescData = protoimpl.X.CompressGZIP(file_protoOneof_proto_rawDescData) }) return file_protoOneof_proto_rawDescData } var file_protoOneof_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_protoOneof_proto_goTypes = []interface{}{ (*WeiboUser)(nil), // 0: oneof_test.WeiboUser (*DouyinUser)(nil), // 1: oneof_test.DouyinUser (*User)(nil), // 2: oneof_test.User } var file_protoOneof_proto_depIdxs = []int32{ 0, // 0: oneof_test.User.weibo_user_info:type_name -> oneof_test.WeiboUser 1, // 1: oneof_test.User.douyin_user_info:type_name -> oneof_test.DouyinUser 2, // [2:2] is the sub-list for method output_type 2, // [2:2] is the sub-list for method input_type 2, // [2:2] is the sub-list for extension type_name 2, // [2:2] is the sub-list for extension extendee 0, // [0:2] is the sub-list for field type_name } func init() { file_protoOneof_proto_init() } func file_protoOneof_proto_init() { if File_protoOneof_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protoOneof_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*WeiboUser); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protoOneof_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*DouyinUser); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protoOneof_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*User); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } file_protoOneof_proto_msgTypes[2].OneofWrappers = []interface{}{ (*User_WeiboUrl)(nil), (*User_DouyinUrl)(nil), (*User_WeiboUserInfo)(nil), (*User_DouyinUserInfo)(nil), } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protoOneof_proto_rawDesc, NumEnums: 0, NumMessages: 3, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protoOneof_proto_goTypes, DependencyIndexes: file_protoOneof_proto_depIdxs, MessageInfos: file_protoOneof_proto_msgTypes, }.Build() File_protoOneof_proto = out.File file_protoOneof_proto_rawDesc = nil file_protoOneof_proto_goTypes = nil file_protoOneof_proto_depIdxs = nil } 测试代码: ...

2022-07-25 · 12 分钟 · czyt