序列化和反序列化在日常工做中会大量使用,然而并不必定很是清楚它的概念。序列化和反序列化的选型倒是系统设计或重构一个重要的环节,在分布式、大数据量系统设计里面更为显著。机器间的通讯须要约定一个协议,序列化和反序列化是这个通讯协议的一部分。
序列化
:将对象或数据结构转为字节序列的过程。
反序列化
:将序列化后生成的字节序列转为对象或数据结构的过程。分布式
比较常见的序列化和反序列化组方式有XML、JSON和Protobuf等。XML标准化较早,基于XML的SOAP是一种应用普遍的结构化数据传递协议。JSON源于js,较之XML它更小、解析更快,并且一样具有可读性好的优势。而源于谷歌的protobuf如今在大型分布式系统普遍使用。大数据
Protobuf是谷歌推出的一款平台无关,语言无关,可扩展的序列化和反序列化技术。ui
要使用Protobuf,首先须要定义.proto文件
以下proto2
中:编码
message msg { required int32 a=1; optional string b=2; repeated string c=3; }
其中:spa
而在proto3
中,字段规则中去除了required和optional,增长singular。可是proto3仍兼容proto2
。设计
message msg { int32 a=1; singular string b=2; repeated string c=3; }
其中,code
一个较完整的.proto文件对象
syntax = "proto3"; message Article { int32 article_id = 1; singular string article_excerpt = 2; repeated string article_picture = 3; singular int32 article_pagecount = 4 [default = 0]; enum ArticleType { NOVEL = 0; PROSE = 1; PAPER = 2; POETRY = 3; } singular ArticleType article_type = 5 [default = NOVEL]; message Author { string name = 1; singular string phone = 2; } singular Author author = 6; repeated int32 article_numberofwords = 7 [packed=true]; reserved 9, 10, 12 to 15; extensions 100 to 1000; } extend Article { singular int32 followers_count = 101; singular int32 likes_count= 102; } message Other { singular string other_info = 1; oneof test_oneof { string code1 = 2; string code2 = 3; } }
咱们总不能都定义在一个文件中。当一个proto文件须要另外一个proto文件的时候,咱们能够经过import导入。protobuf也提供了包的定义,只要在文件开头定义package关键字便可。string
import "test.proto" package foo.bar;
针对不一样语言,依据.proto文件编译成咱们须要的语言文件。如C++下
protoc -I=SRC_DIR --cpp_out=DST_DIR SRC_DIR/ex.proto
先简单记录这些。