http://blog.csdn.net/mycwq/article/details/21864191
protobuf是google的一个序列化框架,类似XML,JSON,其特点是基于二进制,比XML表示同样一段内容要短小得多,还可以定义一些可选字段,广泛用于服务端与客户端通信。文章将着重介绍在erlang中如何使用protobuf。
首先google没有提供对erlang语言的直接支持,所以这里使用到的第三方的protobuf库(erlang_protobuffs)
https://github.com/basho/erlang_protobuffs
定义一个protobuf结构,保存为test.proto,如下:
-
enum PhoneType {
- PhoneType_Home = 1;
- PhoneType_Company = 2;
- }
- message Person {
- required int32 age = 1;
- required string name = 2;
- }
- message Other {
- required PhoneType type = 1;
- required string phone = 2;
- }
- message Family {
- required int32 mainid = 1;
- optional Other other = 2;
- repeated Person person = 3;
- }
编译这个protobuf结构,生成相应的erlang代码:
- % 生成相应的erl和hrl文件
- protobuffs_compile:generate_source("test.proto").
- % 生成相应的beam和hrl文件
- protobuffs_compile:scan_file("test.proto").
下面我们以例子简单说明如何使用:
- -module(test).
- -compile([export_all]).
- -include("test_pb.hrl").
- encode() ->
- Person = #person{age=25, name="John"},
- test_pb:encode_person(Person).
- decode() ->
- Data = erlang:iolist_to_binary(encode()),
- io:format("Data is ~p~n", [Data]),
- test_pb:decode_person(Data).
- encode_repeat() ->
- OtherData = #other{type='PhoneType_Company', phone="028-12345678"},
- RepeatData =
- [
- #person{age=25, name="John"},
- #person{age=23, name="Lucy"},
- #person{age=2, name="Tony"}
- ],
- Family = #family{mainid=111, other=OtherData, person=RepeatData},
- test_pb:encode_family(Family).
- decode_repeat() ->
- Data = erlang:iolist_to_binary(encode_repeat()),
- io:format("Data is ~p~n", [Data]),
- %test_pb:decode_family(Data).
- FamilyData = test_pb:decode_family(Data),
- {family, _, _, PersonData} = FamilyData,
- io:format("~p~n", [FamilyData]),
- io:format("Per Len is ~w~n~n", [length(PersonData)]),
- parse_repeat(PersonData).
- parse_repeat([]) ->
- ok;
- parse_repeat([H|T]) ->
- if is_record(H, person) ->
- io:format("age[~p],name[~p]~n", [H#person.age, H#person.name])
- end,
- parse_repeat(T).
运行代码,如下:
- 5> c(test_pb).
- {ok,test_pb}
- 6> c(test).
- {ok,test}
- 7> test:encode().
- [[["",[25]],[[18],[4],<<"John">>]]]
- 8> test:decode().
-
Data is <<8,25,18,4,74,111,104,110>>
{person,25,"John"} - 9> test:encode_repeat().
-
[[["","o"],
[[18],[16],[[["",[2]],[[18],"f",<<"028-12345678">>]]]],
[[[26],"",[[["",[25]],[[18],[4],<<"John">>]]]],
[[26],"",[[["",[23]],[[18],[4],<<"Lucy">>]]]],
[[26],"",[[["",[2]],[[18],[4],<<"Tony">>]]]]]]] - 10> test:decode_repeat().
Data is <<8,111,18,16,8,2,18,12,48,50,56,45,49,50,51,52,53,54,55,56,26,8,8,25,
18,4,74,111,104,110,26,8,8,23,18,4,76,117,99,121,26,8,8,2,18,4,84,
111,110,121>>
{family,111,
{other,'PhoneType_Company',"028-12345678"},
[{person,25,"John"},{person,23,"Lucy"},{person,2,"Tony"}]}
Per Len is 3age[25],name["John"]
age[23],name["Lucy"]
age[2],name["Tony"]
ok