• protobuf示例


    Google protobuf 是一个高性能的序列化结构化数据存储格式的接口描述语言,具有多语言支持,协议数据小,方便传输,高性能等特点。通过将结构化数据序列化(串行化)成二进制数组,并将二进制数组反序列化成数据对象。用于取代JSONXML,作为服务器通信协议。google 将protobuf协议用于 RPC 系统和持续数据存储系统。Protobuf 的主要优点就是:简单,快。

    1.首先我们需要编写一个 proto 文件,定义我们程序中需要处理的结构化数据,在 protobuf 的术语中,结构化数据被称为 Messageproto 文件非常类似 java 或者 C 语言的数据定义。

    package lm;

    message helloworld

    {

    required int32     id = 1;  // ID

    required string    str = 2;  // str

    optional int32     opt = 3;  //optional field

    }

    2.编译

    protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/addressbook.proto

    3.应用示例

    writer-写入磁盘

    #include "lm.helloworld.pb.h"

    int main(void)

    {

    lm::helloworld msg1;

    msg1.set_id(101);

    msg1.set_str(“hello);

    // Write the new address book back to disk.

    fstream output("./log", ios::out | ios::trunc | ios::binary);

    if (!msg1.SerializeToOstream(&output))

    {

    cerr << "Failed to write msg." << endl;

    return -1;

    }        

    return 0;

    }

    reader-从磁盘读入

    #include "lm.helloworld.pb.h"

    void ListMsg(const lm::helloworld & msg) {

    cout << msg.id() << endl;

    cout << msg.str() << endl;

    }

    int main(int argc, char* argv[]) {

    lm::helloworld msg1;

    {

    fstream input("./log", ios::in | ios::binary);

    if (!msg1.ParseFromIstream(&input)) {

    cerr << "Failed to parse address book." << endl;

    return -1;

    }

    }

    ListMsg(msg1);

    }

    5.缺点

    Protbuf 与 XML 相比也有不足之处。它功能简单,无法用来表示复杂的概念。XML 已经成为多种行业标准的编写工具,Protobuf 只是 Google 公司内部使用的   工具,在通用性上还差很多。

    由于文本并不适合用来描述数据结构,所以 Protobuf 也不适合用来对基于文本的标记文档(如 HTML)建模。另外,由于 XML 具有某种程度上的自解释性,它可以被人直接读取编辑,在这一点上 Protobuf 不行,它以二进制的方式存储,除非你有 .proto 定义,否则你没法直接读出 Protobuf 的任何内容

    原文

    java使用示例

    http://blog.csdn.net/lovexiaozeng336/article/details/8187519

    http://www.ibm.com/developerworks/cn/linux/l-cn-gpb/

    https://code.google.com/p/thrift-protobuf-compare/wiki/Benchmarking

  • 相关阅读:
    控制内插表达式的格式
    MySQL查看实时执行的SQL语句
    测试开源.net 混淆器ConfuserEx
    nginx 目录自动加斜线”/”
    兼职程序员一般可以从什么平台接私活?
    .NET之Hangfire快速入门和使用
    c#通过操作mongodb gridfs实现文件的数据库存储
    c# .net core + .net framework mongodb nuget 包
    asp.net core ModelState 模型状态验证扩展类
    Linux查看系统基本信息,版本信息(最全版)
  • 原文地址:https://www.cnblogs.com/mydomain/p/3175945.html
Copyright © 2020-2023  润新知