C++ protobuf反射特征工程正确姿势


因部门每次加特征,都需要修改 protobuf,添加对应 protobuf获取的代码。重复性开发是真滴多。因此重构获取特征的版本,通过反射+配置动态获取。每次只需升级pb,就可以获取到对应的特征。

1.1 Message

Message 类继承于 MessageLite 类,业务一般自定义的 refactor_reqs 类继承于 Message 类。是自定义的pb类型,继承自Message. MessageLite作为Message基类,更加轻量级一些。

一般使用通过Message的两个接口GetDescriptor/GetReflection,可以获取该类型对应的Descriptor/Reflection。

因为我们的特征都是包含在一个大的Message里头,所以使用FindMessageTypeByName获取Descriptor

const google::protobuf::Reflection* pReflection = pMessage->GetReflection();
const google::protobuf::Descriptor* pDescriptor = pMessage->GetDescriptor();
const ::google::protobuf::Descriptor* pDescriptor =
      google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(msg_name);

1.2 Descriptor

Descriptor是对message类型定义的描述,包括message的名字、所有字段的描述、原始的proto文件内容等。

在类 Descriptor 中,可以通过如下方法获取类 FieldDescriptor:

const FieldDescriptor* field(int index) const; // 根据定义顺序索引获取,即从0开始到最大定义的条目
const FieldDescriptor* FindFieldByNumber(int number) const; // 根据定义的message里面的顺序值获取(option string name=3,3即为number)
const FieldDescriptor* FindFieldByName(const string& name) const; // 根据field name获取
const FieldDescriptor* Descriptor::FindFieldByLowercaseName(const std::string & lowercase_name)const; // 根据小写的field name获取
const FieldDescriptor* Descriptor::FindFieldByCamelcaseName(const std::string & camelcase_name) const; // 根据驼峰的field name获取

1.2 FieldDescriptor

FieldDescriptor描述message中的单个字段,例如字段名,字段属性(optional/required/repeated)等。
对于proto定义里的每种类型,都有一种对应的C++类型

const std::string & name() const; // Name of this field within the message.
CppType cpp_type() const; //C++ type of this field.
bool is_required() const; // 判断字段是否是必填
bool is_optional() const; // 判断字段是否是选填
bool is_repeated() const; // 判断字段是否是重复值
int number() const; // Declared tag number.
int index() const; //Index of this field within the message's field array, or the file or extension scope's extensions array.

1.2 Reflection

Reflection主要提供了动态读写pb字段的接口,对pb对象的自动读写主要通过该类完成

读操作和嵌套的message:

 
  virtual int32  GetInt32 (const Message& message,
                           const FieldDescriptor* field) const = 0;
  virtual int64  GetInt64 (const Message& message,
                           const FieldDescriptor* field) const = 0;
  // See MutableMessage() for the meaning of the "factory" parameter.
  virtual const Message& GetMessage(const Message& message,
                                    const FieldDescriptor* field,
                                    MessageFactory* factory = NULL) const = 0;

对于写操作也是类似的接口,例如SetInt32/SetInt64/SetEnum等。

 void SetInt32(Message * message, const FieldDescriptor * field, int32 value) const

读repeated类型字段:

int32 GetRepeatedInt32(const Message & message, const FieldDescriptor * field, int index) const
std::string GetRepeatedString(const Message & message, const FieldDescriptor * field, int index) const
const Message & GetRepeatedMessage(const Message & message, const FieldDescriptor * field, int index) const

写repeated类型字段:

void SetRepeatedInt32(Message * message, const FieldDescriptor * field, int index, int32 value) const
void SetRepeatedString(Message * message, const FieldDescriptor * field, int index, std::string value) const
void SetRepeatedEnumValue(Message * message, const FieldDescriptor * field, int index, int value) const // Set an enum field's value with an integer rather than EnumValueDescriptor. more..

新增重复字段

void AddInt32(Message * message, const FieldDescriptor * field, int32 value) const
void AddString(Message * message, const FieldDescriptor * field, std::string value) const

2.1 特征工程如何使用

有了上面的知识,我们如何使用到自己的工程中呢。

首先我们定义一个proto文件test_refactor.proto

syntax = "proto3";
package test.refactor;

option cc_generic_services = true;

message item_info {    // item 信息 
    int32 source               = 1;
    repeated int32 newsTypes   = 2;
    string name = 3;
};

message user_info {    // 用户信息
    int32 type           = 1;
    repeated int32 sex   = 2;
    string imei = 3;
};

message item_req {
    item_info item = 1;
    user_info user = 2;
};

message refactor_reqs {
    item_req req = 1;
}
  • 业务场景是所有的特征都包括在message的refactor_reqs中,利用这个message我们可以获取到对应的Descriptor
const ::google::protobuf::Descriptor* descriptor =
      google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName("test.refactor.refactor_reqs");
  • 在获取对应field name获取对应需要获取的FieldDescriptor,如获取item信息的数据,写为req.item

field_descriptor = descriptor->FindFieldByName(“item”);

  • 最终每次获取的时候,我们获取的数据都是填充到test::refactor::refactor_reqs refactor_reqs中。

最终可以得到如下:

3.1 初始化获取FiledDescriptor信息

std::vector<const ::google::protobuf::FieldDescriptor*> GenerateDescriptorSegments(
    const std::string& msg_name, const std::string& pb_path) {
  std::vector<const ::google::protobuf::FieldDescriptor*> descriptor_segments;
  const ::google::protobuf::Descriptor* descriptor =
      google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(msg_name);
  if (descriptor == nullptr) {
    LOG(ERROR) << "get descriptor failed";
  }

  std::vector<std::string> segments;
  boost::split(segments, pb_path, boost::is_any_of("."));
  if (segments.empty()) {
    LOG(ERROR) << "parse pb_path segment empty:" << pb_path;
  }

  // 校验解析数据
  const ::google::protobuf::FieldDescriptor* field_descriptor = NULL;
  for (const auto& segment : segments) {
    if (descriptor == nullptr) {
      LOG(ERROR) << "segment:" << segment << ", descriptor null";
      break;
    }
    // // 根据field name获取
    field_descriptor = descriptor->FindFieldByName(segment);
    if (field_descriptor == nullptr) {
      LOG(ERROR) << "find segment:" << segment << ", descriptor null";
      break;
    }
    // repeate字段暂不支持
    if (field_descriptor->is_repeated()) {
      LOG(ERROR) << " is repeated";
      break;
    }
    descriptor_segments.emplace_back(field_descriptor);
    LOG(INFO) << "cpp_type:" << field_descriptor->cpp_type();
    if (field_descriptor->cpp_type() == ::google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) {
      descriptor = field_descriptor->message_type();
    } else {
      descriptor = nullptr;
    }
  }

  if (field_descriptor == nullptr) {
    // descriptor_segments.clear();
    LOG(ERROR) << "field descriptor null";
  }
  return std::move(descriptor_segments);
}

  • msg_name我们传入test.refactor.refactor_reqs,
  • pb_path解析对应的req.item数据
  • 最终我们可以获取到每个filed对应的FieldDescriptor

3.2 实时获取对应的特征数据

bool ParseFromString(::google::protobuf::Message* last_message,
                 std::vector<const ::google::protobuf::FieldDescriptor*> desc_seg,
                 const std::string& data) {
  auto t1 = butil::gettimeofday_us();
  for (auto& seg : desc_seg) {
    // 处理每一个字段
    auto reflection = last_message->GetReflection();
    // const google::protobuf::Message& submessage = reflection->GetMessage(message, field);
    last_message = reflection->MutableMessage(last_message, seg);
    if (!last_message) {
      LOG(ERROR) << "get message failed, param:";
      break;
    }
  }
  if (!last_message) {
    LOG(ERROR) << "get message failed, key:";
    return false;
  }
  auto suc = last_message->ParseFromString(data);
  LOG(INFO) << "parse suc:" << suc << " feature:" << last_message->Utf8DebugString();
  return suc;
}

  • 将获取到的FieldDescriptor,通过GetReflection逐步初始化。获取到最终数据需要解析的message
  • 最后调用msg->ParseFromString实例化得到最终想要的特征数据

3.3 代码验证

void main() {
  // 构造item特征
  test::refactor::item_info reqs_item;
  reqs_item.set_source(2);
  reqs_item.add_newstypes(3);
  reqs_item.add_newstypes(4);
  reqs_item.set_name("dandyhuang");

  // 构造用户特征
  test::refactor::user_info reqs_user;
  reqs_user.set_imei("dsfdsderw");
  reqs_user.add_sex(3);
  reqs_user.add_sex(4);
  reqs_user.set_type(6666);
	// 从redis获取的item和user特征
  std::string item_data_str = reqs_item.SerializeAsString();
  std::string user_data_str = reqs_user.SerializeAsString();
	
  // 初始化对应需要获取的数据
  auto item_des_seg = GenerateDescriptorSegments("test.refactor.refactor_reqs", "req.item");
  auto user_des_seg = GenerateDescriptorSegments("test.refactor.refactor_reqs", "req.user");
  
  auto t1 = butil::gettimeofday_us();
  // 大proto,获取里头的特征数据
  test::refactor::refactor_reqs refactor_reqs;
  // 解析对应数据
  ParseFromString(&refactor_reqs, item_des_seg, item_data_str);
  LOG(INFO) << "refactor_reqs item:" << refactor_reqs.Utf8DebugString()
            << "name:" << refactor_reqs.req().item().name();
  // 解析对应数据
  ParseFromString(&refactor_reqs, user_des_seg, user_data_str);
  LOG(INFO) << "refactor_reqs user+item:" << refactor_reqs.Utf8DebugString()
            << "imei:" << refactor_reqs.req().user().imei();
  auto t2 = butil::gettimeofday_us();

  // 业务直接解析
  test::refactor::refactor_reqs origin_reqs;
  origin_reqs.mutable_req()->mutable_item()->ParseFromString(item_data_str);
  VLOG(INFO) << "origin_reqs item:" << origin_reqs.Utf8DebugString();
  origin_reqs.mutable_req()->mutable_user()->ParseFromString(user_data_str);
  VLOG(INFO) << "origin_reqs user+item:" << origin_reqs.Utf8DebugString();
  auto t3 = butil::gettimeofday_us();
  VLOG_APP(INFO) << "parse  cost1: " << t2 - t1 << " cost2:" << t3 - t2;
}

4.1 和业务直接解析对比耗时

在这里插入图片描述

我们看到,反射还是比较耗时的,但耗时阶段其实是在构建反射第一次的时候。后续解析pb_path对应的数据时,耗时和直接业务解析是一致的。

当数据量很大,filed_name字段很多的时候,初始化可以另外启动一个线程去初始化。初始化完毕后,在去做特征反射

4.2 每次反射解析ParseFromString的耗时

在这里插入图片描述

大家可以添加我的wx一起交流

我是dandyhuang_,码字不易,有不清楚的可以加w一起交流。

reference

protobuf反射详解

巧用 Protobuf 反射来优化代码,拒做 PB Boy

google protobuf 反射机制学习笔记

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值