最初的疑问是,为什么要用 protobuf ? 而不直接用字节流 ?
字节流也是一种序列化的方式!
以前我们将对象转换为字节流,也要手动写转换API的,而 protobuf 提供了一种可跨平台描述的、较为快速的、且能压缩大小的序列化方式。
面向接口编程,主要用于对外做逻辑抽象,外部只调用抽象接口,而不管内部如何实现。
这样就算未来整个内存的实现方式都变了,也不影响上层的使用。
2016.11.6 关于序列化的补充:
序列化是将一个对象或者对象图转换成一个字节流的过程:
- 使应用程序的状态可以轻松保存到磁盘文件或数据库上;
- 通过网络将对象发送到其他进程中,还可以用来跨越AppDomain的边界;
- 一旦对象序列化成了内存中的字节流,还可以更方便地对其进行加密、压缩等;
.Net 二进制序列化示例:
using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SerializeTest { class Program { private static MemoryStream SerializeToMemory(object objectGraph) { var stream = new MemoryStream(); var formatter = new BinaryFormatter(); formatter.Serialize(stream, objectGraph); return stream; } private static object DeserializeFromMemory(Stream binaryStream) { var formatter = new BinaryFormatter(); return formatter.Deserialize(binaryStream); } static void Main(string[] args) { var objectGraph = new List<string> { "Jeff", "Kristin", "Aidan", "Grant" }; Stream stream = SerializeToMemory(objectGraph); objectGraph = null; stream.Seek(0, SeekOrigin.Begin); objectGraph = (List<string>)DeserializeFromMemory(stream); foreach(var s in objectGraph) { Console.WriteLine(s); } Console.ReadKey(); } } }
为什么都用 google 的 protofbuf?
贴一篇前人的试验参考:http://www.cnblogs.com/smark/archive/2012/05/06/2485656.html。