java序列化 KRYO框架

由于做序列化,JDK自带的序列化方法效率较低,最后采用了Kryo 来序列化。
演示demo如下:
先导入依赖:

 <dependency>
        <groupId>com.esotericsoftwaregroupId>
        <artifactId>kryoartifactId>
        <version>4.0.0version>
    dependency>
    
    <dependency>
        <groupId>com.esotericsoftwaregroupId>
        <artifactId>kryo-shadedartifactId>
        <version>4.0.0version>
    dependency>

然后是Demo

package com.thomas.testmaven;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

/**
 * Created by lee on 16/8/29.
 */
public class KryoUtil
{
    private static final ThreadLocal KRYO_THREAD_LOCAL =
            new ThreadLocal(){
                @Override
                protected Kryo initialValue()
                {
                    return new Kryo();
                }
            };

    public static  byte[] writeObject(T obj, int maxBufferSize)
    {
        Kryo kryo = KRYO_THREAD_LOCAL.get();
        Output output = new Output(maxBufferSize);
        kryo.writeObject(output, obj);
        output.flush();
        output.close();
        return output.toBytes();
    }

    public static  T readObject(byte[] bytes, Class cls)
    {
        Kryo kryo = KRYO_THREAD_LOCAL.get();
        Input input = new Input(bytes);
        return kryo.readObject(input, cls);
    }


    public static void main(String[] args)
    {
        for(int i = 0; i < 5; ++i)
        {
            KryoThread kryoThread = new KryoThread("Thread-" + i);
            kryoThread.start();
        }
    }


    public static class KryoThread extends Thread
    {
        public KryoThread(String name)
        {
            super(name);
        }

        @Override
        public void run()
        {
            for(int i = 0; i < 10; ++i)
            {
                Person person = new Person(i, "name" + i, 20 + i);
                byte[] bytes = KryoUtil.writeObject(person, 100);
                System.out.println(getName() + " writing...");
                Person result = KryoUtil.readObject(bytes, Person.class);
                System.out.println(getName() + " reading...");
                System.out.println("result:  ");
                System.out.println(result.toString());
            }
        }
    }
}

简单的用法,具体高级功能参见官方文档(https://github.com/EsotericSoftware/kryo)

你可能感兴趣的:(随笔)