Protobuf

2018-02-28  本文已影响0人  第八共同体

1.简介

Protobuf是Protocol Buffers的简称,它是Google公司开发的一种数据描述语言,用于序列化结构化数据 - 类似XML,但更小,更快,更简单。 您可以定义数据的结构化结构,然后使用特殊生成的源代码轻松地将结构化数据写入和读取各种数据流,并使用各种语言。可以作为RPC的基础工具

2.定义一个Message类型

/* SearchRequest represents a search query, with pagination options to
 * indicate which results to include in the response. */
syntax = "proto3";
message SearchRequest {
    string query = 1;
    int32 page_number = 2; // Which page number do we want?
    int32 result_per_page = 3;// Number of results to return per page.
}
message Foo {
   reserved 2, 15, 9 to 11;
   reserverd "foo", "bar";
}

注意,不能在同一保留语句中混合字段名称和标记号。

编译后产出的文件

对于go,产生一个.pb.go文件

3.标量类型

.proto type ====> GO type
double            float64
float             float
int32/sint32/sfixed32      int32
int64/sint64/sfixed64      int64
uint32/fixed32    uint32
uint64/fixed64    uint64
bool              bool
string            string
bytes             []byte

4.默认值

5.Enumerations

message SearchRequest {
  string query = 1;
  int32 page_number = 2;
  int32 result_per_page = 3;
  enum Corpus {
    UNIVERSAL = 0;
    WEB = 1;
    IMAGES = 2;
    LOCAL = 3;
    NEWS = 4;
    PRODUCTS = 5;
    VIDEO = 6;
  }
  Corpus corpus = 4;
}

Corpus字段是一个枚举类型,第一个常量影射为0.每个枚举类型必需包含一个常量映射为0,作为第一个元素。
可以定义一个别名通过分配同样的值给不同的枚举常量。这么做首先需要设置allow_alias选项为true.否则会报错。

enum EnumAllowingAlias {
  option allow_alias = true;
  UNKNOWN = 0;
  STARTED = 1;
  RUNNING = 1;
}

6.使用其他message类型

可以使用其他message 类型作为字段类型。例如,Result 作为SearchResponse的字段。

message SearchResponse {
    repeated Result results = 1;
}
message Result {
    string url = 1;
    string title = 2;
    repeated string snippets = 3;
}

上面两个类型定义在同一个.proto文件中,如果Result定义在另一个文件中呢?
在需要导入其他文件定义的文件中头部

import "myproject/other_protos.proto";

7.嵌套类型

message SearchResponse {
    message Result {
        string url = 1;
        string title = 2;
        repeated string snippets = 3;
    }
    repeated Result results = 1;
}

如果想重用在父类型之外的其他类型中,使用Parent.Type;

message SomeOtherMessage {
    SearchResponse.Result result = 1;
}

嵌套深度无限制。

8.更新一个Messsage

如果一个类型不满足需求了,比如需要添加额外的字段。但是依然使用原来的形式,如下:

9.oneof

oneof字段就像常规的字段,除了oneof中的字段共享内存,任何时候,只有一个字段的值被设置。设置任何一个字段,会自动清除其他成员。你可查询那个字段设置了,使用case()或者WhichOneof() 方法,根据你选择的语言。

message SampleMessage {
  oneof test_oneof {
    string name = 4;
    SubMessage sub_message = 9;
  }
}
上一篇 下一篇

猜你喜欢

热点阅读