【转载】在erlang项目中使用protobuf

来源:互联网 发布:nginx body filter 编辑:程序博客网 时间:2024/04/30 09:28

protobuf是google的一个序列化框架,类似XML,JSON,其特点是基于二进制,比XML表示同样一段内容要短小得多,还可以定义一些可选字段,广泛用于服务端与客户端通信。文章将着重介绍在erlang中如何使用protobuf。

首先google没有提供对erlang语言的直接支持,所以这里使用到的第三方的protobuf库(erlang_protobuffs)

定义一个protobuf结构,保存为test.proto,如下:

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. message Person {  
  2.   required int32 age = 1;  
  3.   required string name = 2;  
  4. }  
  5.   
  6. message Family {  
  7.   repeated Person person = 1;  
  8. }  
编译这个protobuf结构,生成相应的erlang代码:
[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. % 生成相应的erl和hrl文件  
  2. protobuffs_compile:scan_file_src("test.proto").  
  3.   
  4. % 生成相应的beam和hrl文件  
  5. protobuffs_compile:scan_file("test.proto").  

下面我们以例子简单说明如何使用:

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. -module(test).  
  2.   
  3. -compile([export_all]).  
  4.   
  5. -include("test_pb.hrl").  
  6.   
  7. encode() ->  
  8.     Person = #person{age=25, name="John"},  
  9.     test_pb:encode_person(Person).  
  10.   
  11. decode() ->  
  12.     Data = encode(),  
  13.     test_pb:decode_person(Data).  
  14.   
  15. encode_repeat() ->  
  16.     RepeatData =  
  17.     [  
  18.         #person{age=25, name="John"},  
  19.         #person{age=23, name="Lucy"},  
  20.         #person{age=2, name="Tony"}  
  21.     ],  
  22.     Family = #family{person=RepeatData},  
  23.     test_pb:encode_family(Family).  
  24.       
  25. decode_repeat() ->  
  26.     Data = encode_repeat(),  
  27.     test_pb:decode_family(Data).  
运行代码,如下:

 

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. 6> c(test).  
  2. {ok,test}  
  3.   
  4. 7> test:encode().  
  5. <<8,25,18,4,74,111,104,110>>  
  6.   
  7. 8> test:decode().  
  8. {person,25,"John"}  
  9.   
  10. 9> test:encode_repeat().  
  11. <<10,8,8,25,18,4,74,111,104,110,10,8,8,23,18,4,76,117,99,  
  12.   121,10,8,8,2,18,4,84,111,110,...>>  
  13.   
  14. 10> test:decode_repeat().  
  15. {family,[{person,25,"John"},  
  16.          {person,23,"Lucy"},  
  17.          {person,2,"Tony"}]}  

 

作者:【没有开花的树】
出处:http://blog.csdn.net/mycwq/article/details/42060641

0 0
原创粉丝点击