org.macrocloud.kernel.toolkit.utils.ProtostuffUtil Maven / Gradle / Ivy
package org.macrocloud.kernel.toolkit.utils;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
/**
* Protostuff 工具类.
*
* @author macro
*/
public class ProtostuffUtil {
/** 避免每次序列化都重新申请Buffer空间. */
private static final LinkedBuffer BUFFER = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
/** 缓存Schema. */
private static final Map, Schema>> SCHEMA_CACHE = new ConcurrentHashMap<>();
/**
* 序列化方法,把指定对象序列化成字节数组.
*
* @param T
* @param obj obj
* @return byte[]
*/
@SuppressWarnings("unchecked")
public static byte[] serialize(T obj) {
Class clazz = (Class) obj.getClass();
Schema schema = getSchema(clazz);
byte[] data;
try {
data = ProtostuffIOUtil.toByteArray(obj, schema, BUFFER);
} finally {
BUFFER.clear();
}
return data;
}
/**
* 反序列化方法,将字节数组反序列化成指定Class类型.
*
* @param T
* @param data data
* @param clazz clazz
* @return T
*/
public static T deserialize(byte[] data, Class clazz) {
Schema schema = getSchema(clazz);
T obj = schema.newMessage();
ProtostuffIOUtil.mergeFrom(data, obj, schema);
return obj;
}
/**
* 获取Schema.
*
* @param T
* @param clazz clazz
* @return T
*/
@SuppressWarnings("unchecked")
private static Schema getSchema(Class clazz) {
Schema schema = (Schema) SCHEMA_CACHE.get(clazz);
if (Objects.isNull(schema)) {
//这个schema通过RuntimeSchema进行懒创建并缓存
//所以可以一直调用RuntimeSchema.getSchema(),这个方法是线程安全的
schema = RuntimeSchema.getSchema(clazz);
if (Objects.nonNull(schema)) {
SCHEMA_CACHE.put(clazz, schema);
}
}
return schema;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy