protobuf的GZIP压缩
protobuf自带压缩功能,可选的压缩算法有 GZIP 和 ZLIB
序列化至iostream
序列化示例:
std::ofstream output("scene.art", std::ofstream::out | std::ofstream::trunc | std::ofstream::binary);
OstreamOutputStream outputFileStream(&output);
GzipOutputStream::Options options;
options.format = GzipOutputStream::GZIP;
options.compression_level = _COMPRESSION_LEVEL;
GzipOutputStream gzipOutputStream(&outputFileStream, &options);
scene->SerializeToZeroCopyStream(&gzipOutputStream);
反序列化示例:
std::ifstream input("scene.art", std::ifstream::in | std::ifstream::binary);
IstreamInputStream inputFileStream(&input);
GzipInputStream GzipInputStream(&inputFileStream);
scene1->ParseFromZeroCopyStream(&GzipInputStream);
序列化至string
序列化示例:
#include <google/protobuf/io/gzip_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
std::string output;
// 压缩序列化
google::protobuf::io::GzipOutputStream::Options options;
options.format = google::protobuf::io::GzipOutputStream::GZIP;
options.compression_level = 9;
google::protobuf::io::StringOutputStream outputStream(&output);
google::protobuf::io::GzipOutputStream gzipStream(&outputStream, options);
person.SerializeToZeroCopyStream(&gzipStream)
gzipStream.Close(); //数据刷到储存中
反序列化示例:
google::protobuf::io::ArrayInputStream inputStream(output.data(), output.size());
google::protobuf::io::GzipInputStream gzipStream(&inputStream);
person.ParseFromZeroCopyStream(&gzipStream)
需要注意:
1)序列化需要用 StringOutputStream ,对应的反序列化需要用 ArrayInputStream 。没有StringinputStream类。源码中的说明如下:

2)压缩序列化的时候,必须进行 Close 或者 Flush 操作
参考链接:
protobuf 启用 GZIP 压缩功能
本文介绍了如何使用protobuf进行GZIP压缩。在序列化protobuf消息到iostream或string时,可以利用GzipOutputStream和GzipInputStream进行压缩和解压缩操作。在序列化过程中,需设置 compression_level 和 format,然后使用Close或Flush确保数据被写入。反序列化时,通过ArrayInputStream读取已压缩的string。注意序列化用StringOutputStream,反序列化用ArrayInputStream。

4994

被折叠的 条评论
为什么被折叠?



