kryo对于普通对象(包括类)的序列化和反序列化的示例代码一:
jar包可以到官网上下载。官网的地址:http://code.google.com/p/kryo/
static private void bean3() {
Kryo kryo = new Kryo();
// kryo.setReferences(true);
// kryo.setRegistrationRequired(true);
// kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());
//注册类
Registration registration = kryo.register(Student.class);
long time = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
//序列化
Output output = null;
// ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//output = new Output( outStream , 4096);
output = new Output(1, 4096);
Student student = new Student("zhangsan", "man", 23);
kryo.writeObject(output, student);
byte[] bb = output.toBytes();
// System.out.println(bb.length);
output.flush();
//反序列化
Input input = null;
// input = new Input(new
// ByteArrayInputStream(outStream.toByteArray()),4096);
input = new Input(bb);
Student s = (Student) kryo.readObject(input, registration.getType());
System.out.println(s.getName()+","+s.getSex());
input.close();
}
time = System.currentTimeMillis() - time;
System.out.println("time:" + time);
}
序列化的速度比java更快,更是在缓存区占用更少。
bean类:
package com.test;
import java.io.Serializable;
public class Student implements Serializable{
private String name;
private String sex;
private int age;
public Student() {
}
public Student(String name, String sex, int age) {
super();
this.name = name;
this.sex = sex;
this.age = age;
}
public String getName() {
return name;
}
public String getSex() {
return sex;
}
public int getAge() {
return age;
}
}