protobuf

模板

syntax = "proto3"; // 指定 protobuf 的版本  
  
package example; // 定义包名  
  
// 导入其他 protobuf 文件  
import "google/protobuf/timestamp.proto";  
import "other_package/other_file.proto";  
  
// 定义一个枚举类型  
enum State {  
 UNKNOWN = 0; // 枚举值必须从 0 开始  
 STARTED = 1;  
 RUNNING = 2;  
 STOPPED = 3;  
}  
  
// 定义一个消息类型  
message Person {  
 // 定义一个字符串字段  
 string name = 1; // 字段编号必须是唯一的正整数  
  
 // 定义一个整型字段  
 int32 id = 2; // 这里的 2 是字段编号  
  
 // 定义一个布尔字段  
 bool has_pony = 3;  
  
 // 定义一个浮点字段  
 float salary = 4;  
  
 // 定义一个枚举字段  
 State state = 5;  
  
 // 定义一个重复字段(类似于列表)  
 repeated string emails = 6;  
  
 // 定义一个嵌套消息  
 message Address {  
   string line1 = 1;  
   string line2 = 2;  
   string city = 3;  
   string country = 4;  
   string postal_code = 5;  
 }  
  
 // 定义一个嵌套消息字段  
 Address address = 7;  
  
 // 定义一个 map 字段(类似于字典)  
 map<string, string> phone_numbers = 8;  
  
 // 定义一个任意类型字段  
 google.protobuf.Any any_field = 9;  
  
 // 定义一个时间戳字段  
 google.protobuf.Timestamp last_updated = 10;  
  
 // 定义一个从其他文件导入的消息类型字段  
 other_package.OtherMessage other_field = 11;  
  
 // 定义一个 oneof 字段,可以设置其中一个字段  
 oneof test_oneof {  
   string name = 12;  
   int32 id = 13;  
   bool is_test = 14;  
 }  
}  
  
// 定义一个服务  
service ExampleService {  
 // 定义一个 RPC 方法,请求类型为 GetPersonRequest 响应类型为 Person  
 rpc GetPerson(GetPersonRequest) returns (Person);  
}  
  
// 定义 GetPerson RPC 方法的请求消息类型  
message GetPersonRequest {  
 int32 person_id = 1;  
}

特别注意

  1. 字段编号一旦被分配后就不应更改,为了保持向后兼容性
  2. 编号在 [1,15] 范围内的字段编号在序列化时只占用一个字节。因此,为了优化性能,对于频繁使用的字段,尽可能使用该范围内的数字。同时也要为未来可能添加的常用字段预留一些编号(不要一股脑把 15 之内的编号都用了!)
  3. 字段号 19000,19999 是为 Protocol Buffers 实现保留的。
  4. 保留字段:如果你通过完全删除字段或将其注释来更新消息类型,则未来其他开发者对类型进行自己的更新时就有可能重用字段编号。当旧版本的代码遇到新版本生成的消息时,由于字段编号的重新分配,可能会引发解析错误或不预期的行为。为了避免这种潜在的兼容性问题,protobuf 提供 reserved 关键字来明确标记不再使用的字段编号或标识符,如果将来的开发者尝试使用这些标识符,proto 编译器将会报错提醒。
message Foo {
  reserved 2, 15, 9 to 11, 40 to max;
  // 9 to 11 表示区间 [9,11], 40 to max 表示区间 [40, 编号的最大值]
  reserved "foo", "bar";
}
posted @ 2024-06-16 23:42  叒狗  阅读(35)  评论(0编辑  收藏  举报