protocal buffers入门实例

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("[email protected]")
				.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");
		}
						
	}

}

 

 

你可能感兴趣的:(实例,protoc,protocal buffer)