Last active
September 2, 2016 07:03
-
-
Save yangl/7409416 to your computer and use it in GitHub Desktop.
kryo序列化工具类,推荐实用protostuff,FST!https://gist.github.com/yangl/17154726c959a483e725 http://www.protostuff.io/documentation/runtime-schema/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.jd.market.easypayservice.common.util.mapper; | |
import com.esotericsoftware.kryo.Kryo; | |
import com.esotericsoftware.kryo.io.Input; | |
import com.esotericsoftware.kryo.io.Output; | |
import org.objenesis.strategy.StdInstantiatorStrategy; | |
import java.io.ByteArrayInputStream; | |
import java.io.ByteArrayOutputStream; | |
import java.io.IOException; | |
/** | |
* kryo序列化工具类 | |
* | |
* | |
* @author YANGLiiN | |
* @date 2013-04-07 09:57 | |
*/ | |
public abstract class KryoMapper { | |
private static ThreadLocal<Kryo> kryos = new ThreadLocal<Kryo>() { | |
@Override | |
protected Kryo initialValue() { | |
Kryo kryo = new Kryo(); | |
// kryo.setRegistrationRequired(false); | |
// kryo.setReferences(true); | |
// kryo.setInstantiatorStrategy(new StdInstantiatorStrategy()); | |
return kryo; | |
} | |
}; | |
private static Kryo get() { | |
return kryos.get(); | |
} | |
// 序列化object-->byte[] | |
public static byte[] toByteArray(Object object) throws IOException { | |
ByteArrayOutputStream bos = new ByteArrayOutputStream(); | |
Output output = new Output(bos); | |
Kryo kryo = get(); | |
// writeObjectOrNull object.getClass() | |
kryo.writeClassAndObject(output, object); | |
byte[] bs = output.toBytes(); | |
bos.close(); | |
output.close(); | |
return bs; | |
} | |
// 反序列化byte[]-->t | |
public static <T> T toObject(byte[] bs) throws IOException { | |
ByteArrayInputStream bis = new ByteArrayInputStream(bs); | |
Input input = new Input(bis); | |
Kryo kryo = get(); | |
T t = (T) kryo.readClassAndObject(input); | |
bis.close(); | |
input.close(); | |
return t; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment