美文网首页
Protobuf 3

Protobuf 3

作者: warmyouth | 来源:发表于2018-06-04 11:42 被阅读0次
syntax = "proto3";
message SearchRequest {
  string query = 1;
  int32 page_number = 2;
  int32 result_per_page = 3;
}

field:singular,repeated。在proto2中,field有required,optional,repeated;在proto3中,repeated是默认packed的(和proto2不同)。
field number:115和type一起压缩在1个字节,162047和type需要2个字节。
为保证proto文件向后兼容,过时的field number或者field name需要打上reserved的标签,比如

message Foo {
  reserved 2, 15, 9 to 11;
  reserved "foo", "bar";
}

type:基本类型如下:

float double int32 int64 uint32 uint64 bool string bytes 
sint32 sint64 sfixed32 sfixed64 fixed32 fixed64

其中,string只支持ASCII和UTF-8;对于这些类型的默认值,取0/空字符串/空字节流/空列表,message的默认值和语言实现相关。
Enumerations的注意点:

  1. 首个定义的值必须为0(可以作为默认值);
  2. 要求在int32的范围内,不推荐负数;
  3. 如果需要多对一,则需要加入optional allow_alias = true,比如
enum EnumAllowingAlias {
  option allow_alias = true;
  UNKNOWN = 0;
  STARTED = 1;
  RUNNING = 1;
}

引入:import "myproject/user.proto";
引入的搜索路径:用--proto_path指明,或者为调用protoc的路径。
嵌套类型:

message Outer {                  // Level 0
  message MiddleAA {  // Level 1
    message Inner {   // Level 2
      int64 ival = 1;
      bool  booly = 2;
    }
  }
  message MiddleBB {  // Level 1
    message Inner {   // Level 2
      int32 ival = 1;
      bool  booly = 2;
    }
  }
}

Oneof fields are like regular fields except all the fields in a oneof share memory, and at most one field can be set at the same time. Setting any member of the oneof automatically clears all the other members. You can check which value in a oneof is set (if any) using a special case() or WhichOneof() method, depending on your chosen language.

Defining Services(an RPC system,Remote Procedure Call)

You can define an RPC service interface in a .proto file and the protocol buffer compiler will generate service interface code and stubs in your chosen language.
For example, if you want to define an RPC service with a method that takes your SearchRequest and returns a SearchResponse, you can define it in your .proto file as follows:

service SearchService {
  rpc Search (SearchRequest) returns (SearchResponse);
}

The most straightforward RPC system to use with protocol buffers is gRPC: a language- and platform-neutral open source RPC system developed at Google. gRPC works particularly well with protocol buffers and lets you generate the relevant RPC code directly from your .proto files using a special protocol buffer compiler plugin.
If you don't want to use gRPC, it's also possible to use protocol buffers with your own RPC implementation. You can find out more about this in the Proto2 Language Guide.

JSON Mapping

Proto3 supports a canonical encoding in JSON, making it easier to share data between systems.

相关文章

网友评论

      本文标题:Protobuf 3

      本文链接:https://www.haomeiwen.com/subject/wqvesftx.html