Protocol Buffers动态自描述消息的用法

来源:互联网 发布:大学生网络政治参与 编辑:程序博客网 时间:2024/05/13 19:27

Google Protocol Buffer( 简称 Protobuf) 是 Google 公司内部的混合语言数据标准,目前已经正在使用的有超过 48,162 种报文格式定义和超过 12,183 个 .proto 文件。他们用于 RPC 系统和持续数据存储系统。
Protocol Buffers 是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,或者说序列化。它很适合做数据存储或 RPC 数据交换格式。可用于通讯协议、数据存储等领域的语言无关、平台无关、可扩展的序列化结构数据格式。目前提供了 C++、Java、Python 三种语言的 API。
关于Protocol Buffers的基础用法网上介绍的已经比较多了,只需要提前定义好.proto文件编译之后直接使用即可。但是这种传统的用法在某些特定的场合下还是存在一定的局限性的,有些时候我们需要去修改定义的.proto文件,甚至不能提前确定好消息的具体内容。因而能够动态的去编译或者解析proto文件就显得很有必要了,庆幸的是Google Protocol Buffers为开发者提供了这些支持。让我们能够在一些特定的场合动态的去使用Protocol Buffers,下面我将介绍一种Protocol Buffers的动态自描述消息的使用方法。
首先,什么事动态自描述消息呢?在讲动态自描述消息之前需要先提两个概念:
1.自描述消息:简单的来说就是能够在运行期去动态的解析.proto文件的消息,这样就解放了消费者,即当消息的内容有变动的时候也不用去更改消费者的代码,使用起来更加的方便。
Protobuf 提供了 google::protobuf::compiler 包来完成动态编译的功能。主要的类叫做 importer,定义在 importer.h 中。使用 Importer 非常简单,下图展示了与 Import 和其它几个重要的类的关系。
Importer 类
首先构造一个 importer 对象。构造函数需要两个入口参数,一个是 source Tree 对象,该对象指定了存放 .proto 文件的源目录。第二个参数是一个 error collector 对象,该对象有一个 AddError 方法,用来处理解析 .proto 文件时遇到的语法错误。
之后,需要动态编译一个 .proto 文件时,只需调用 importer 对象的 import 方法。非常简单。
2.动态消息:简单的来说就是连.proto文件都不用定义了,因为消息的定义可以直接在运行期执行,这样就解放了生产者,可以适应哪些我们并不能提前确定消息具体内容的场合。
Package google::protobuf::compiler 中提供了以下几个类,用来表示一个 .proto 文件中定义的 message,以及 Message 中的 field,如图所示。
各个 Compiler 类之间的关系
类 FileDescriptor 表示一个编译后的 .proto 文件;类 Descriptor 对应该文件中的一个 Message;类 FieldDescriptor 描述一个 Message 中的一个具体 Field。
动态自描述消息就是把上面两者结合,在生产端可以动态的定义消息的同时,消费端也可以动态的去解析消息。这样,就同时解放了生产者和消费者。下面是具体的实现方式
以下面消息为例说明:
message pair {
required string key = 1;
required uint32 value = 2;
}
生产者和消费者商定文件格式如下:

这里写图片描述
程序代码如下:

//////kimgbo///#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <iostream>#include <string>#include <google/protobuf/descriptor.h>#include <google/protobuf/descriptor.pb.h>#include <google/protobuf/dynamic_message.h>#include <google/protobuf/io/zero_copy_stream.h>#include <google/protobuf/io/zero_copy_stream_impl.h>#include <google/protobuf/io/coded_stream.h>using namespace std;using namespace google::protobuf;using namespace google::protobuf::io;//校验值const unsigned int MAGIC_NUM=2988;void encode(){    //定义一个foo.proto文件    FileDescriptorProto file_proto;    file_proto.set_name("foo.proto");    //创建一个消息类型 Pair    DescriptorProto *message_proto = file_proto.add_message_type();    message_proto->set_name("Pair");    //给消息类型添加若干 filed    FieldDescriptorProto *field_proto = NULL;    field_proto = message_proto->add_field();    field_proto->set_name("key");    field_proto->set_type(FieldDescriptorProto::TYPE_STRING);    field_proto->set_number(1);    field_proto->set_label(FieldDescriptorProto::LABEL_REQUIRED);    field_proto = message_proto->add_field();    field_proto->set_name("value");    field_proto->set_type(FieldDescriptorProto::TYPE_UINT32);    field_proto->set_number(2);    field_proto->set_label(FieldDescriptorProto::LABEL_REQUIRED);    //添加并构建此message到proto文件中    DescriptorPool pool;    const FileDescriptor *file_descriptor = pool.BuildFile(file_proto);    const Descriptor *descriptor = file_descriptor->FindMessageTypeByName("Pair");    cout << descriptor->DebugString();    //动态创建一个Pair类型的message    DynamicMessageFactory factory(&pool);    const Message *message = factory.GetPrototype(descriptor);    // create a real instance of "Pair"    Message *pair = message->New();    //赋值    const Reflection *reflection = pair->GetReflection();    const FieldDescriptor *field = NULL;    field = descriptor->FindFieldByName("key");    reflection->SetString(pair, field, "my key");    field = descriptor->FindFieldByName("value");    reflection->SetUInt32(pair, field, 1234);    //内容序列化后存到dpb.msg    int fd = open("dpb.msg", O_WRONLY|O_CREAT,0666);    //ZeroCopyOutputStream据说实现了零拷贝    ZeroCopyOutputStream* raw_output = new FileOutputStream(fd);    CodedOutputStream* coded_output = new CodedOutputStream(raw_output);    coded_output->WriteLittleEndian32(MAGIC_NUM);    string data;    file_proto.SerializeToString(&data);    coded_output->WriteVarint32(data.size());    coded_output->WriteString(data);    data.clear();    pair->SerializeToString(&data);    coded_output->WriteVarint32(data.size());    coded_output->WriteString(data);    delete coded_output;    delete raw_output;    close(fd);}void decode(){    //反序列化    FileDescriptorProto file_proto;    int fd = open("dpb.msg", O_RDONLY);    ZeroCopyInputStream* raw_input = new FileInputStream(fd);    CodedInputStream* coded_input = new CodedInputStream(raw_input);    //校验是否序列化成功    unsigned int magic_number;    coded_input->ReadLittleEndian32(&magic_number);    if (magic_number != MAGIC_NUM)     {        cerr << "File not in expected format." << endl;        return;    }    uint32 size;    coded_input->ReadVarint32(&size);     char* text = new char[size + 1];    coded_input->ReadRaw(text, size);    text[size] = '\0';    file_proto.ParseFromString(text);    DescriptorPool pool;    const FileDescriptor *file_descriptor = pool.BuildFile(file_proto);    const Descriptor *descriptor = file_descriptor->FindMessageTypeByName("Pair");    // build a dynamic message by "Pair" proto    DynamicMessageFactory factory;    const Message *message = factory.GetPrototype(descriptor);    // create a real instance of "Pair"    Message *pair = message->New();    coded_input->ReadVarint32(&size);    text = new char[size + 1];    coded_input->ReadRaw(text, size);    text[size] = '\0';    pair->ParseFromString(text);    cout << pair->DebugString();    delete pair;}int main(int argc, char* argv[]){    encode();    decode();    return 0;}   

当然这种使用方法提高编程便捷性的同时是以损失了时间和空间为代价,所以并没有什么绝对优越的使用方式,只不过是针对的使用场景不同罢了。

参考:《玩转Protocol Buffers 》

1 0
原创粉丝点击