Skip to content

Instantly share code, notes, and snippets.

@yangl
Last active August 29, 2015 14:07
Show Gist options
  • Save yangl/17154726c959a483e725 to your computer and use it in GitHub Desktop.
Save yangl/17154726c959a483e725 to your computer and use it in GitHub Desktop.
FST序列化反序列化工具。拿当前项目订单数据序列化、反序列化100万次和JDK序列化工具比较耗时相差不到一个数据级:---SerializationUtils.serialize---193565 ---FSTSerializationUtils.serialize---33351
package com.iuni.order.common.mapper;
import org.nustaq.serialization.FSTObjectInput;
import org.nustaq.serialization.FSTObjectOutput;
import java.io.*;
// 3.0可用下边这个简单的接口了,FST并不支持添加删除字段!
// FSTCoder fst = new DefaultCoder();
// fst.toByteArray
// fst.toObject
/**
*
* Static utilities for serialization and deserialization by FST.
*
* @author YAGNLiiN
* @date 2014-10-20 13:33
*/
public abstract class FSTSerializationUtils {
/**
* Serialize the given object to a byte array.
*
* @param object the object to serialize
* @return an array of bytes representing the object in a portable fashion
*/
public static byte[] serialize(Object object) {
if (object == null) {
return null;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
FSTObjectOutput out = null;
try {
out = new FSTObjectOutput(baos);
out.writeObject(object);
} catch (IOException ex) {
throw new IllegalArgumentException("FST: Failed to serialize object of type: " + object.getClass(), ex);
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
}
}
return baos.toByteArray();
}
/**
* Deserialize the byte array into an object.
*
* @param bytes a serialized object
* @return the result of deserializing the bytes
*/
public static Object deserialize(byte[] bytes) {
if (bytes == null) {
return null;
}
FSTObjectInput in = null;
try {
in = new FSTObjectInput(new ByteArrayInputStream(bytes));
return in.readObject();
} catch (IOException ex) {
throw new IllegalArgumentException("FST: Failed to deserialize object", ex);
} catch (ClassNotFoundException ex) {
throw new IllegalStateException("FST: Failed to deserialize object type", ex);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment