kryo序列化

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import org.objenesis.strategy.StdInstantiatorStrategy;

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

public class DefaultSerializeConverter
{
    private ThreadLocal<Kryo> serializeThreadLocal = new ThreadLocal<Kryo>();
   
    private static DefaultSerializeConverter instance = new DefaultSerializeConverter();
   
    public static DefaultSerializeConverter getInstance() {
        return instance;
    }
   
    private DefaultSerializeConverter() {
       
    }
   
    public Kryo getSerializeConverter() {
        Kryo kryo = serializeThreadLocal.get();
       
        if (kryo == null) {
            kryo = new Kryo();
            kryo.setRegistrationRequired(true);
            kryo.setReferences(true);
            kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());
           
            kryo.register(Class.class);
            kryo.register(HashMap.class);
            kryo.register(ArrayList.class);
            kryo.register(BigDecimal.class);
            kryo.register(Date.class);
           
            serializeThreadLocal.set(kryo);
        }
        return kryo;
    }
   
    public byte[] toBytes(Object t) {
        Kryo converter = getSerializeConverter();
        Output output = new Output(1024, 4 * 1024);
        converter.writeObject(output, t);

        return output.toBytes();
    }
   
    public <T> T fromBytes(byte[] bytes, Class<T> clazz) {
        Kryo converter = getSerializeConverter();
        Input input = new Input(bytes);
        return converter.readObject(input, clazz);
    }
   
}

你可能感兴趣的:(企业应用)