java原生序列化和Kryo序列化性能比较 以及Kryo使用方法

时间:2022-10-15 07:42:01

原文引自 : https://www.cnblogs.com/520playboy/p/6341490.html

Netty 序列化类 Kyro:

public class RaceUtils {
    //写
    public static byte[] writeKryoObject(Object object) {
        Output output = new Output(1024);
        Kryo kryo = new Kryo();
        kryo.writeObject(output, object);
        output.flush();
        output.close();
        byte [] ret = output.toBytes();
        output.clear();
        return ret;
    }
    //读
    public static <T> T readKryoObject(Class<T> tClass, byte[] bytes) {
        Kryo kryo = new Kryo();
        Input input = new Input(bytes);
        input.close();
        T ret = kryo.readObject(input, tClass);
        return ret;
    }

}

具体使用方法:

//写
Student stu = new Student("wency",19);
byte [] body = RaceUtils.writeKryoObject(obj);
//读
byte [] body = xxxx;
Student stu = RaceUtils.readKryoObject(Student.class, body);