关于protobuf:proto语法说明

2次阅读

共计 1582 个字符,预计需要花费 4 分钟才能阅读完成。

官网文档:https://developers.google.cn/…

一、根本语法示例

/*
  头部相干申明
*/
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_3…
  • https://www.jianshu.com/p/6a6…
正文完
 0