高性能序列化protostuff

来源:互联网 发布:声音剪辑合成软件 编辑:程序博客网 时间:2024/06/04 23:22


protostuff基于Google protobuf,但是提供了更多的功能和更简易的用法。

protobuf的一个缺点是需要数据结构的预编译过程,首先要编写.proto格式的配置文件,再通过protobuf提供的工具生成各种语言响应的代码。

由于java具有反射和动态代码生成的能力,这个预编译过程不是必须的,可以在代码执行时来实现。这就是protostuff


SerializationUtils1

import com.dyuproject.protostuff.LinkedBuffer;import com.dyuproject.protostuff.ProtostuffIOUtil;import com.dyuproject.protostuff.Schema;import com.dyuproject.protostuff.runtime.RuntimeSchema;import org.objenesis.Objenesis;import org.objenesis.ObjenesisStd;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;/** * * 使用protostuff进行序列化和反序列化 */public class SerializationUtils {    private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<Class<?>, Schema<?>>();    private static Objenesis objenesis = new ObjenesisStd(true);    private SerializationUtils() {    }    //对象 转 字节数组   序列化    public static <T> byte[] serialize(T obj) {        Class<T> clazz = (Class<T>) obj.getClass();//获得对象的类        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);//使用LinkedBuffer分配一块默认大小的buffer空间        try {//通过对象的类构建对应的schema            Schema<T> schema = getSchma(clazz);            return ProtostuffIOUtil.toByteArray(obj, schema, buffer);//使用给定的schema将对象序列化为一个byte数组,并返回        } finally {            buffer.clear();        }    }    private static <T> Schema<T> getSchma(Class<T> clazz) {        Schema<T> schema = (Schema<T>) cachedSchema.get(clazz);//构建schema的过程比较耗时,使用map将schema缓存起来        if (schema == null) {            schema = RuntimeSchema.createFrom(clazz);            cachedSchema.put(clazz, schema);        }        return schema;    }    //字节数组 转 对象   反序列化    public static <T> T deserialize(byte[] data, Class<T> clazz) {        T message = objenesis.newInstance(clazz);//使用objenesis实例化一个类的对象        Schema<T> schma = getSchma(clazz);//通过对象的类构建对应的schema        ProtostuffIOUtil.mergeFrom(data, message, schma);//使用给定的schema将byte数组和对象合并        return message;    }}


SerializationUtils2
import com.dyuproject.protostuff.LinkedBuffer;import com.dyuproject.protostuff.ProtostuffIOUtil;import com.dyuproject.protostuff.Schema;import org.objenesis.Objenesis;import org.objenesis.ObjenesisStd;/** * * 使用protostuff进行序列化和反序列化 */public class SerializationUtils2 {    private static SchemaCache schemaCache = SchemaCache.getInstance();    private static Objenesis objenesis = new ObjenesisStd(true);    private SerializationUtils2() {    }    //对象 转 字节数组   序列化    public static <T> byte[] serialize(T obj) {        Class<T> clazz = (Class<T>) obj.getClass();//获得对象的类        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);//使用LinkedBuffer分配一块默认大小的buffer空间        try {//通过对象的类构建对应的schema            Schema<T> schema = getSchma(clazz);            return ProtostuffIOUtil.toByteArray(obj, schema, buffer);//使用给定的schema将对象序列化为一个byte数组,并返回        } finally {            buffer.clear();        }    }    private static <T> Schema<T> getSchma(Class<T> clazz) {        Schema<T> schema = (Schema<T>) schemaCache.get(clazz);        return schema;    }    //字节数组 转 对象   反序列化    public static <T> T deserialize(byte[] data, Class<T> clazz) {        T message = objenesis.newInstance(clazz);//使用objenesis实例化一个类的对象        Schema<T> schma = getSchma(clazz);//通过对象的类构建对应的schema        ProtostuffIOUtil.mergeFrom(data, message, schma);//使用给定的schema将byte数组和对象合并        return message;    }}
SchemaCache
import com.dyuproject.protostuff.Schema;import com.dyuproject.protostuff.runtime.RuntimeSchema;import com.google.common.cache.Cache;import com.google.common.cache.CacheBuilder;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.TimeUnit;public class SchemaCache {    //使用单例模式,构建缓存类    private static class SchemaCacheHolder {        private static SchemaCache cache = new SchemaCache();    }    public static SchemaCache getInstance() {        return SchemaCacheHolder.cache;    }    /*    使用cacheBuilder生成器生成缓存    maximumSize:缓存如果达到限额,则回收(接近时就会启动回收)    expireAfterAccess:缓存在给定时间没有被访问,则回收     */    private Cache<Class<?>, Schema<?>> cache = CacheBuilder.newBuilder()            .maximumSize(1024).expireAfterAccess(1, TimeUnit.HOURS)            .build();    /*    cache.get(k,Callable)方法返回缓存中的值,或者使用call方法将结果加入到缓存中。     */    private Schema<?> get(final Class<?> clazz, Cache<Class<?>, Schema<?>> cache) {        try {            return cache.get(clazz, new Callable<RuntimeSchema<?>>() {                public RuntimeSchema<?> call() throws Exception {                    return RuntimeSchema.createFrom(clazz);                }            });        } catch (ExecutionException e) {            return null;        }    }    public Schema<?> get(final Class<?> clazz) {        return get(clazz, cache);    }}





由于protostuff的schema中包含了对象进行序列化和反序列化的逻辑,所以构建过程比较耗时,这边需要使用缓存来做优化。
utils1中使用了concurrenthashmap作为缓存
utils2中使用了google的guava中的cache。
两者各有优劣
concurrenthashmap速度快,但是不能自动对内存进行有效控制,如果元素过多,存在内存风险
guava可以通过配置限制使用的内存大小,效率也比较快

大家可以根据具体的业务场景,来考虑应用哪一个缓存。


原创粉丝点击