proto语法说明

官方文档:https://developers.google.cn/protocol-buffers/docs/proto3

一、基本语法示例

/*
  头部相关声明
*/
syntax = "proto3"; // 语法版本为protobuf3.0
package = "com.xxx.foo"; // 定义包名
import "common.proto"; // 导入common.proto
option 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_32237719/article/details/99854208
  • https://www.jianshu.com/p/6a6dbff2b5cd
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天空还下着雪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值