Protobuf高级用法 - Options以及Extensions

首先先说结论,Protobuf目前支持files, messages, enums以及services的options的定义。


File Options:

这个应该是最基本的,我们可以看到在很多protobuf的源文件proto里都有如下的写法


最简单的,他给我们带来了定义包名package name的options. 这些options是在compile time就被protoc根据对应的plugin读取的


Message Options:

Message Options分两种情况:

  1. 对应整个Message,比如
  2. Message Field Options - 针对单个具体的field 同时可以观察,profanedb.proto.options带了括号,表示是自己extend的options,不是预定义的


Enum Options / Service Options:

这两种方式实际跟Message定义Options的方式类似,比如



Custom Options:

需要实现custom options的前提是你要对extensions做过了解

syntax = "proto2";

import "google/protobuf/descriptor.proto";

package profanedb.protobuf; // These options should be used during schema definition, applying them to some of the fields in protobuf

message FieldOptions { optional bool key = 1; }

extend google.protobuf.FieldOptions

{ optional FieldOptions options = 1036; }

这里的package非常关键,他表示我们要使用他们的方式,比如这里的package profanedb.protobuf,当我们要使用这个扩展的field options的时候,我们就可以这么来引用

[ (profanedb.protobuf.options).key = true ];

可以看到这里的profanedb发挥了一定的作用


同时可以看到我们这里使用的是extend
google.protobuf.FieldOptions,当然除了FieldOptions之外,我们还能extend MessageOptions, EnumOptions, ServiceOptions等。同时需要注意这里的序号用的是1036,实际上从50000-99999可以在日常开发中使用,当你要真正的去release你的项目的时候,你需要告诉Google,让其给你分配一个唯一的号。


在使用Custom Options之前,我们需要清晰的区别出message filed options和message fields本身的区别:

  • Message Fields是定义在我们的message ... { ... }结构体里,他们定义在proto文件中
  • Message Fields提供给你的是具体的structure,同时你可以通过一定的内容进行填充
  • Message Fields Options是Message的一种declaration
  • Message Fields Options会给message field declaration追加对应的metadata以及context


用Protobuf的术语来说,当我们在一个proto文件中创建一个message,我们就构造出了一个Descriptor.任何在这个Message中定义的field就会成为一个FieldDescriptor.因此我们会有如下这些Descriptor

  • FileDescriptor -> proto file
  • Descriptor -> Message
  • FieldDescriptor -> Field


这些Descriptors都会提供一个叫options()的方法,他会返回对应的FileOptions, MessageOptions, FiledOptions以及custom options.我们可以用GetExtension()来判断是否定义了某个option

// Check whether a Descriptor has a field with key option set

bool Loader::IsKeyable(const google::protobuf::Descriptor * descriptor) const

{

for (int i = 0; i < descriptor->field_count(); i++) {

// If any field in message has profanedb::protobuf::options::key set

if (descriptor->field(i)->options().GetExtension(profanedb::protobuf::options).key())

return true;

}

return false;

}

原文链接:,转发请注明来源!