分布式RPC通信:protobuf序列化和反序列化

  • Protobuf

    protobuf(protocol buffer)是google 的一种数据交换的格式,它独立于平台语言。
    google 提供了protobuf多种语言的实现:java、c#、c++、go 和 python,每一种实现都包含了相应语
    言的编译器以及库文件。
    由于它是一种二进制的格式,比使用 xml(20倍) 、json(10倍)进行数据交换快许多。可以把它用
    于分布式应用之间的数据通信或者异构环境下的数据交换。作为一种效率和兼容性都很优秀的二进制数
    据传输格式,可以用于诸如网络传输、配置文件、数据存储等诸多领域。

    ubuntu protobuf 环境搭建

    github源代码下载地址:https://github.com/google/protobuf
    源码包中的src/README.md,有详细的安装说明,安装过程如下:
    1、解压压缩包:unzip protobuf-master.zip
    2、进入解压后的文件夹:cd protobuf-master
    3、安装所需工具:sudo apt-get install autoconf automake libtool curl make g++ unzip
    4、自动生成configure配置文件:./autogen.sh
    5、配置环境:./configure
    6、编译源代码(时间比较长):make

    7、安装:sudo make install
    8、刷新动态库:sudo ldconfig

    Protobuf实践

    创建如下目录:

    test.proto内容为:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    ![2_test_1](D:\Dream\PRC通信\2_test_1.png)syntax = "proto3"; // 声明了protobuf的版本,syntax翻译是"语法"

    package protest; // 声明了代码所在的包(相当于C++的namespace)

    // 定义登陆请求消息类型 name pwd
    message LoginRequest
    {
    string name = 1;
    string pwd = 2;
    }

    // 定义登陆响应消息类型
    message LoginResponse
    {
    int32 errcode = 1;
    string errmsg = 2;
    bool result = 3;
    }

    执行 protoc test.proto –cpp_out=./

    1
    2
    3
    4
    5
    6
    z@zzz:~/Z/RPC/test/protobuf$ ls
    main.cc test.proto
    z@zzz:~/Z/RPC/test/protobuf$ protoc test.proto --cpp_out=./
    z@zzz:~/Z/RPC/test/protobuf$ ls
    main.cc test.pb.cc test.pb.h test.proto
    z@zzz:~/Z/RPC/test/protobuf$

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    #include "test.pb.h"
    #include <iostream>

    int main()
    {
    protest::LoginRequest req;
    req.set_name("zhang san");
    req.set_pwd("123456");

    std::string sendStr;
    if (req.SerializeToString(&sendStr)) {
    std::cout << sendStr << std::endl;
    }

    return 0;
    }

    执行 g++ main.cc test.pb.cc -lprotobuf

    • 施磊——【高级】C++项目-实现分布式网络通信框架-rpc通信原理