当前位置:首页 > 开发 > 系统架构 > 架构 > 正文

protocal buffers入门实例

发表于: 2014-09-22   作者:blackproof   来源:转载   浏览:
摘要: hadoop yarn中新的系列化protocol buffers 1.安装protoc,附件里是win,llinux的文件,win配置下环境变量,或是linux下configure make make install 2.写protoc文件person.proto package tutorial; option java_package="";//包名 optio

hadoop yarn中新的系列化protocol buffers

1.安装protoc,附件里是win,llinux的文件,win配置下环境变量,或是linux下configure make make install

2.写protoc文件person.proto

package tutorial;
option java_package="";//包名
option java_outer_classname="PersonProtos";//类名

message Person{
	required string name = 1;  //required为必填,optional为可为空
	required int32 id =2;   
	required string email = 3;
	
	message PhoneNumber{
		required string number = 1;
		optional int32 type = 2;
	}
	
	repeated PhoneNumber phone = 4;
}

2.protoc命令生成类到当前目录

protoc -java_out=. person.proto

 3.测试类

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import com.zb.demo.protocalBuffers.PersonProtos.Person;

/**
 * proto buffer实例
 * @author dirk.zhang
 *
 */
public class ProtocalBufferExample {
	
	public static void main(String[] args) {
		Person person1 = Person.newBuilder()
				.setName("dirk.zhang")
				.setEmail("kongzhiguiji@aliyun.com")
				.setId(41)
				.addPhone(Person.PhoneNumber.newBuilder().setNumber("13522616858")
						.setType(0))
						.addPhone(Person.PhoneNumber.newBuilder().setNumber("110").setType(1)).build();
		
		
		try {
			FileOutputStream output = new FileOutputStream(new File("d:\\delete\\protobufExample.txt"));
			person1.writeTo(output);
			output.close();
		} catch (Exception e) {
			System.out.println("write Error!");
		}
		try {
			FileInputStream input = new FileInputStream(new File("d:\\delete\\protobufExample.txt"));
			Person person2 = Person.parseFrom(input);
			System.out.println("person2:"+person2);
		} catch (Exception e) {
			System.out.println("read Error");
		}
						
	}

}

 

 

protocal buffers入门实例

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号