官网文档:https://developers.google.cn/...
一、根本语法示例
/* 头部相干申明*/syntax = "proto3"; // 语法版本为protobuf3.0package = "com.xxx.foo"; // 定义包名import "common.proto"; // 导入common.protooption java_package = "com.xxx.foo"; // 指定java包// 搜寻申请message SearchRequest{ int32 page = 1; // 当前页 int32 page_size = 2; // 一页多少条,应用下划线分隔,设置的时候应用驼峰命令法,如:setPageSize(10); enum Type { IN = 0; // 0须要是第一个,第一个也是默认值 OUT = 1; } Type type = 3; // 类型}// 搜寻响应message SearchResponse{ int32 code = 1; // 状态码 string message = 2; // 音讯 SearchList data = 3; // 数据,类型为SearchList}// SearchList构造message SearchList{ repeated Item data = 1; // 数据记录项,repeated类型用来寄存N个雷同类型的内容 int64 count = 2; // 总条数 int32 page_size = 3; // 一页条数}// Item构造message Item{ int64 id = 1; // id string title = 2; // 题目 int64 create_time = 3; // 创立工夫 int64 update_time = 4; // 更新工夫}// 服务service SearchService{ rpc GetSearchList(SearchRequest) returns (SearchResponse); // rpc 办法}
命令标准倡议应用下面示例
字段类型有:
二、字段修饰符
- singular:单个的,有0个或1个(默认)
- repeated:反复的,反复任意次数
- required:要求的
- optional:可选的
- reserved:保留的,保留字段名或字段号
message Foo { reserved 2, 15, 9 to 11; reserved "foo", "bar"; string foo = 3 // 编译报错,因为‘foo’曾经被标为保留字段}
[warning] 留神:不能在同一个reserved
语句中同时应用字段名和字段号。
三、嵌套
message SearchResponse { message Result { string id = 1; string title = 2; } repeated Result results = 1;}
四、援用
message OtherMessage { SearchResponse.Result result = 1;}
五、应用Any类型
须要导入import google/protobuf/any.proto
import "google/protobuf/any.proto";message ErrorStatus { string message = 1; repeated google.protobuf.Any details = 2;}
六、oneof
oneof
除了共享内存中的所有字段外,oneof
字段与惯例字段相似,并且最多能够同时设置一个字段。
message TestMessage { oneof test_oneof { int32 id = 1; string title = 2; }}
七、零碎默认值
- string默认为空字符串
- bool默认为false
- 数值默认为0
- enum默认为第一个元素
欢送关注:https://fenxianglu.cn/
参考链接:
- https://blog.csdn.net/baidu_3...
- https://www.jianshu.com/p/6a6...