protobuf使用介绍

一:环境准备

1:maven 中获取protobuf-java 2.6.1

<dependency>
		  <groupId>com.google.protobuf</groupId>
		  <artifactId>protobuf-java</artifactId>
		  <version>2.6.1</version>
</dependency>

 2:protobuf 代码生成工具下载

见附件

3:AadSocketMsg.proto 文件准备

package netty;  
option java_package = "com.suning.aad.common.protobuf";  
option java_outer_classname = "AadSocketMsgProto"; 

message AadSocketMsg{
	required string socketMsgType =1;
	required string ip=2;
	optional string appName=3;
	optional string appPath=4;
	optional string logPath=5;
	optional string appType=6;
	optional string appBackUpPath=7;
	optional string startPath=8;
	optional string stopPath=9;
	optional string restartPath=10;
	optional string upLoadHdfsPath=11;
	optional string downHdfsPath=12;
	optional string zookeeperPath=13;
}

java_package 指定java包路径

 java_outer_classname  生成java 文件的类名及文件名 

扫描二维码关注公众号,回复: 389867 查看本文章

required 为必填项

optional 为可选项

二:生成java 代码

运行protoc.exe,即命令行 protoc   -I={输入目录}   --cpp_out={输出目录}   ASpace.A.proto   ,生成ASpace.A.pd.h和ASpace.A.pb.cc

//protoc  -I=.\   --cpp_out=.\   ASpace.A.proto

 

三、测试验证类

package com.suning.aad.common.protobuf;

import com.google.protobuf.InvalidProtocolBufferException;

public class ProtoMain {
	
	public static void main(String[] args){
		
		AadSocketMsgProto.AadSocketMsg req = create();
		
		System.out.println("before encode:" + req.toString());
		
		try {
			AadSocketMsgProto.AadSocketMsg req2 = AadSocketMsgProto.AadSocketMsg.parseFrom(req.toByteArray());
		
			System.out.println("after encode--->decode:" + req2.toString());
			
			System.out.println("assert equal:" + req2.equals(req));
		} catch (InvalidProtocolBufferException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
	
	}
	


public static AadSocketMsgProto.AadSocketMsg create(){
		AadSocketMsgProto.AadSocketMsg.Builder builder = AadSocketMsgProto.AadSocketMsg.newBuilder();
		
		builder.setIp("127.0.0.1");
		builder.setSocketMsgType("333");
		builder.setZookeeperPath("/yyl/zookeeper");
		
		return builder.build();
	}
	
	
}

 

猜你喜欢

转载自yylcslg.iteye.com/blog/2289440