1.protocol buff是一种协议,是谷歌推出的一种序列化协议
2.Java序列化协议也是一种协议
3.两者的目的是,将对象序列化成字节数组,或者说是二进制数据
java序列化示例
public class JAVA2Bytes {
public static void main(String[] args) throws Exception {
byte[] bytes = toBytes();
toPlayer(bytes);
}
/**
* 序列化
* @throws IOException
*/
public static byte[] toBytes() throws IOException{
//新建一个Player类
Player player = new Player(101, 20, "peter");
player.getSkills().add(1001);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
//写入对象
objectOutputStream.writeObject(player);
//获取 字节数组
byte[] byteArray = byteArrayOutputStream.toByteArray();
System.out.println(Arrays.toString(byteArray));
return byteArray;
}
/**
* 反序列化
* @param bs
* @throws Exception
*/
public static void toPlayer(byte[] bs) throws Exception{
ObjectInputStream inputStream = new ObjectInputStream(new ByteArrayInputStream(bs));
Player player = (Player)inputStream.readObject();
//打印
System.out.println("playerId:" + player.getPlayerId());
System.out.println("age:" + player.getAge());
System.out.println("name:" + player.getName());
System.out.println("skills:" + (Arrays.toString(player.getSkills().toArray())));
}
}
protocol buffer序列化实例
1 定义要序列化的对象
option java_package = "com.proto";
option java_outer_classname = "PlayerModule";
message PBPlayer{
required int64 playerId = 1;
required int32 age = 2;
required string name = 3;
repeated int32 skills = 4;
}
message PBResource{
required int64 gold = 1;
required int32 energy = 2;
}
2.使用protoc.exe生成PlayerModule
类
3.使用protocol进行序列化
public class PB2Bytes {
public static void main(String[] args) throws Exception {
byte[] bytes = toBytes();
toPlayer(bytes);
}
/**
* 序列化
*/
public static byte[] toBytes(){
//获取一个PBPlayer的构造器
Builder builder = PlayerModule.PBPlayer.newBuilder();
//设置数据
builder.setPlayerId(101).setAge(20).setName("jay").addSkills(1001);
//构造出对象
PBPlayer player = builder.build();
//序列化成字节数组
byte[] byteArray = player.toByteArray();
System.out.println("系列化后生成的数组:"+Arrays.toString(byteArray));
return byteArray;
}
/**
* 反序列化
* @param bs
* @throws Exception
*/
public static void toPlayer(byte[] bs) throws Exception{
PBPlayer player = PlayerModule.PBPlayer.parseFrom(bs);
System.out.println("playerId:" + player.getPlayerId());
System.out.println("age:" + player.getAge());
System.out.println("name:" + player.getName());
System.out.println("skills:" + (Arrays.toString(player.getSkillsList().toArray())));
}
}