1、Java序列化的缺点
1、无法跨语言;
2、序列化后的码流太大;
测试代码如下:
package com.netty.pojo;
import java.io.Serializable;
import java.nio.ByteBuffer;
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private int id;
public User buildName(String name) {
this.name = name;
return this;
}
public User buildId(int id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
/**
* 运用 ByteBuffer 的二进制编解码技术对 User 对象进行编码
* @return
*/
public byte[] codeC(ByteBuffer buffer) {
buffer.clear();
byte[] value = this.name.getBytes();
buffer.putInt(value.length);
buffer.put(value);
buffer.putInt(this.id);
buffer.flip();
value = null;
byte[] result = new byte[buffer.remaining()];
buffer.get(result);
return result;
}
}
package com.netty.codec;
import com.netty.pojo.User;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
public class TestUser {
public static void main(String[] args) throws IOException {
User u = new User();
u.buildId(100).buildName("Welcome to Netty");
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(u);
os.flush();
os.close();
byte[] b = out.toByteArray();
System.out.println("The jdk serializable length is : " + b.length);
out.close();
System.out.println("-----------------------------------------");
ByteBuffer buffer = ByteBuffer.allocate(1024);
System.out.println("The ByteBuffer serializable length is : " + u.codeC(buffer).length);
}
}
运行结果:
jdk编码是 二进制编码方式的 4倍。
3、序列化性能太低;
测试代码如下:
package com.netty.codec;
import com.netty.pojo.User;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
public class PerformTestUser {
public static void main(String[] args) throws IOException {
User u = new User();
u.buildId(100).buildName("Welcome to Netty");
int loop = 100_0000;
ByteArrayOutputStream out;
ObjectOutputStream os;
long startTime = System.currentTimeMillis();
for (int i = 0; i < loop; i++) {
out = new ByteArrayOutputStream();
os = new ObjectOutputStream(out);
os.writeObject(u);
os.flush();
os.close();
byte[] b = out.toByteArray();
out.close();
}
long endTime = System.currentTimeMillis();
System.out.println("The jdk serializable cost time is : " + (endTime - startTime) + " ms");
System.out.println("-----------------------------------------");
startTime = System.currentTimeMillis();
ByteBuffer buffer = ByteBuffer.allocate(1024);
for (int i=0;i<loop;i++) {
byte[] b = u.codeC(buffer);
}
endTime = System.currentTimeMillis();
System.out.println("The ByteBuffer serializable cost time is : " + (endTime - startTime) + " ms");
}
}
运行结果:
结果很明显,jdk编码速度很差。
2、业界主流的编解码框架
1、Google的 Protobuf
2、Facebook 的 Thrift
3、JBoss Marshalling