protobuf 作为配置文件

公司每个project代码中,都有一个Config类,作为模块启动的配置。其实现如下

struct Config {
 int num;
 char * file_name;
 int load_from_file(const char* filename);
}
int Config::load_from_file(const char* filename)
{
   ConfigDom dom;
   parse_node_from_file(&dom, filename);
   get_value("num", dom, this->num);
   get_value("filename", dom, this->file_name);

}

每次添加配置项,需要在在类config中添加字段,还需要添加对该字段的解析,从定义中看,字段名写了三次。能否写一次就解决问题呢?

 

其实,在业界有两种方案解决,一种是基于google flags的解决方案,通过命令行参数传递,这个适合参数比较少的情况(当然基于GNU的getopts也可以,个人感觉没有gflags好用)。

还有一种就是今天需要介绍的protobuf了。protobuf提供了一种textformat的序列化格式,类似json格式,清晰易读。

步骤如下

1. 定义protobuf

2. 编译之

3. 按照json格式定义配置,在代码中读入文件,解析之成protobuf结构

4. 通过protobuf结构引用变量。

无须其它工作,方便。

 

posted @ 2014-08-16 15:23  westfly  阅读(1563)  评论(0编辑  收藏  举报