Erlang uses protobuf In the Erlang Project

Source: Internet
Author: User

Protobuf is a serialization framework of Google. Similar to XML and JSON, protobuf is based on binary and is much shorter than XML to indicate the same content. You can also define some optional fields, it is widely used for communication between the server and the client. This article focuses on how to use protobuf in Erlang.

First, Google does not provide direct support for the Erlang language, so the third-party protobuf Library (erlang_protobuffs) used here)

Define a protobuf structure and save it as test. proto, as follows:

message Person {  required int32 age = 1;  required string name = 2;}message Family {  repeated Person person = 1;}

Compile the protobuf structure and generate the corresponding Erlang code:

% 生成相应的erl和hrl文件protobuffs_compile:scan_file_src("test.proto").% 生成相应的beam和hrl文件protobuffs_compile:scan_file("test.proto").

The following is an example of how to use it:

-module(test).-compile([export_all]).-include("test_pb.hrl").encode() ->Person = #person{age=25, name="John"},test_pb:encode_person(Person).decode() ->Data = encode(),test_pb:decode_person(Data).encode_repeat() ->RepeatData =[#person{age=25, name="John"},#person{age=23, name="Lucy"},#person{age=2, name="Tony"}],Family = #family{person=RepeatData},test_pb:encode_family(Family).decode_repeat() ->Data = encode_repeat(),test_pb:decode_family(Data).

Run the Code as follows:

6> c(test).{ok,test}7> test:encode().<<8,25,18,4,74,111,104,110>>8> test:decode().{person,25,"John"}9> test:encode_repeat().<<10,8,8,25,18,4,74,111,104,110,10,8,8,23,18,4,76,117,99,  121,10,8,8,2,18,4,84,111,110,...>>10> test:decode_repeat().{family,[{person,25,"John"},         {person,23,"Lucy"},         {person,2,"Tony"}]}

Erlang uses protobuf In the Erlang Project

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.