protostuff基于Google protobuf,其中,protostuff-runtime实现了无需预编译的Java Bean进行protobuf序列化/反序列化的能力。
对于仅适用Java语言,且无需跨语言的适用场景,protostuff继承了Google protobuf的高性能的同事免去了编写.proto文件的麻烦,是非常值得推荐的序列化/反序列化方案。
代码如下:
package ares.remoting.framework.serialization.serializer.impl;
import ares.remoting.framework.serialization.serializer.ISerializer;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author fuss created on 18/7/23.
* @version $Id$
*/
public class ProtoStuffSerializer implements ISerializer {
private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<Class<?>, Schema<?>>();
@SuppressWarnings("unchecked")
private static <T> Schema<T> getSchema(Class<T> cls) {
Schema<T> schema = (Schema<T>) cachedSchema.get(cls);
if (schema == null) {
schema = RuntimeSchema.createFrom(cls);
cachedSchema.put(cls, schema);
}
return schema;
}
@SuppressWarnings("unchecked")
public <T> byte[] serialize(T obj) {
Class<T> cls = (Class<T>) obj.getClass();
LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
try {
Schema<T> schema = getSchema(cls);
return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
buffer.clear();
}
}
public <T> T deserialize(byte[] data, Class<T> cls) {
try {
T message = (T) cls.getConstructors()[0].newInstance();
Schema<T> schema = getSchema(cls);
ProtostuffIOUtil.mergeFrom(data, message, schema);
return message;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
maven依赖,代码如下:
<!-- Protostuff -->
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.0.9</version>
</dependency>