文章目录
一、概述
由于分布式需要在不同的主机之间进行通信,因此需要对信息进行打包。打包之后发送的数据称为“序列化”信息,接受方接收到序列化信息之后,需要进行“反序列化”得到结构化的信息。
protobuf 正是提供了这两个过程的一个库。
二、protobuf 的安装
1. 获取源码:https://github.com/google/protobuf
2. 源码包中的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 的功能:
1. 创建test.proto文件:
syntax = "proto3"; // 声明proto的版本
package fixbug; // 声明了代码所在的包
// 定义登录请求消息类型
message LoginRequest{
bytes name = 1;
bytes pwd = 2;
}
// 定义登录响应消息类型
message LoginRespone{
int32 errcode = 1;
bytes errmsg = 2;
bool success = 3;
}
2. 对test.proto进行编译
这里编译的作用生成相对应的C++代码来给程序进行调用。命令:
protoc test.proto --cpp_out ./
其中,protoc 是编译命令,test.proto是文件名,./ 是指定了当前的路径
编译之后会增加两个文件 test.pb.cc 和 test.pb.h(忽略main.cc 和 a.out):
3. 使用main函数测试功能
#include <iostream>
#include <string>
#include "test.pb.h" // 引入之前生成的库
using namespace fixbug; // 解开命名空间
int main() {
LoginRequest req; // 创建对象
req.set_name("zhang san"); // 设置
req.set_pwd("123456"); // 设置
// 序列化为string
std::string send_str;
if (req.SerializeToString(&send_str)) {
std::cout << send_str.c_str() << std::endl;
}
// 从string反序列化
LoginRequest reqB;
if (reqB.ParseFromString(send_str)) {
std::cout << reqB.name() << std::endl;
std::cout << reqB.pwd() << std::endl;
}
return 0;
}
3.1 编译
g++ main.cc test.pb.cc -lprotobuf // 注意一定要动态连接
3.2 运行
./a.out
3.3 输出结果
完成收工!!!