netty-jdk序列化和二进制序列化
摘自<netty权威指南>
java序列化的目的主要有:
- 网络传输
- 对象持久化
现有POJO为UserDo
:
public class UserDo implements Serializable {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] codec() {
ByteBuffer byteBuf = ByteBuffer.allocate(1024);
byte[] val = this.name.getBytes();
byteBuf.putInt(val.length);
byteBuf.put(val);
byteBuf.putInt(this.age);
byteBuf.flip();
val = null;
byte[] rs = new byte[byteBuf.remaining()];
byteBuf.get(rs);
return rs;
}
public byte[] codec(ByteBuffer byteBuf ) {
byteBuf.clear();
byte[] val = this.name.getBytes();
byteBuf.putInt(val.length);
byteBuf.put(val);
byteBuf.putInt(this.age);
byteBuf.flip();
val = null;
byte[] rs = new byte[byteBuf.remaining()];
byteBuf.get(rs);
return rs;
}
}
测试案例
public class UserDoSerializableTest {
public static void main(String[] args) throws Exception{
serializableTest();
performanceTest();
}
private static void performanceTest() throws Exception{
UserDo userDo = new UserDo();
userDo.setAge(12);
userDo.setName("netty");
int loop = 1000000;
long start = System.currentTimeMillis();
ByteArrayOutputStream baos ;
ObjectOutputStream oos;
for (int i = 0; i < loop; i++) {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(userDo);
oos.flush();
oos.close();
}
System.out.println("the jdk serializable cost time is "
+(System.currentTimeMillis()-start)+ " ms");
start = System.currentTimeMillis();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
for (int i = 0; i < loop; i++) {
byte[] codec = userDo.codec(byteBuffer);
}
System.out.println("the byte array serializable cost time is "
+(System.currentTimeMillis()-start)+ " ms");
}
private static void serializableTest() throws IOException {
UserDo userDo = new UserDo();
userDo.setAge(12);
userDo.setName("netty");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(userDo);
oos.flush();
oos.close();
byte[] array = baos.toByteArray();
System.out.println("jdk serializable length is : "+ array.length);
baos.close();
System.out.println("--------------------------------------------");
System.out.println("byte array serializable length is : "+ userDo.codec().length);
}
}
运行结果
--------serializable test----------
jdk serializable length is : 107
byte array serializable length is : 13
--------performance test----------
the jdk serializable cost time is 2883 ms
the byte array serializable cost time is 174 ms
从运行结果来看,jdk自带的序列化机制和性能都差强人意