java 序列化工具类

  1. protostuff序列化方式


package com.example.demo.pro;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;

import com.sf.fvp.util.ProtostuffRuntimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ProtostuffUtil {
    private static final Logger logger = LoggerFactory.getLogger(ProtostuffUtil.class);
    private static final int linkedBufferQueueSize = 512;
    private static final int linkedBufferSize = 512;
    private static final Map<String, Schema> schemas = new ConcurrentHashMap();
    private static final BlockingQueue<LinkedBuffer> linkedBufferPoolQueue = new ArrayBlockingQueue(512);

    public ProtostuffUtil() {
    }

    public static <T> byte[] serialize(T data) {
        Class clazz = data.getClass();
        Schema schema = getSchema(clazz);
        LinkedBuffer linkedBuffer = null;

        byte[] protostuff;
        try {
            linkedBuffer = (LinkedBuffer)linkedBufferPoolQueue.take();
            protostuff = ProtostuffIOUtil.toByteArray(data, schema, linkedBuffer);
        } catch (InterruptedException var13) {
            logger.error("serialize error, Class=" + clazz, var13);
            throw new RuntimeException(var13);
        } finally {
            if (linkedBuffer != null) {
                linkedBuffer.clear();

                try {
                    linkedBufferPoolQueue.put(linkedBuffer);
                } catch (InterruptedException var12) {
                    logger.error("put linkedBuffer error, Class=" + clazz, var12);
                }
            }

        }

        return protostuff;
    }

    public static <T> List<byte[]> serialize(List<T> datas) {
        if (datas != null && !datas.isEmpty()) {
            List<byte[]> results = new ArrayList(datas.size());
            Class clazz = datas.get(0).getClass();
            Schema schema = getSchema(clazz);
            LinkedBuffer linkedBuffer = null;

            try {
                linkedBuffer = (LinkedBuffer)linkedBufferPoolQueue.take();
                Iterator var5 = datas.iterator();

                while(var5.hasNext()) {
                    T data = (T) var5.next();
                    results.add(ProtostuffIOUtil.toByteArray(data, schema, linkedBuffer));
                    linkedBuffer.clear();
                }
            } catch (InterruptedException var14) {
                logger.error("serialize error, Class=" + clazz, var14);
                throw new RuntimeException(var14);
            } finally {
                if (linkedBuffer != null) {
                    linkedBuffer.clear();

                    try {
                        linkedBufferPoolQueue.put(linkedBuffer);
                    } catch (InterruptedException var13) {
                        logger.error("put linkedBuffer error, Class=" + clazz, var13);
                    }
                }

            }

            return results;
        } else {
            return null;
        }
    }

    public static <T> T deSerialize(Class<T> clazz, byte[] data) {
        if (clazz != null && data != null) {
            Schema schema = getSchema(clazz);
            Object t = null;

            try {
                t = clazz.newInstance();
                ProtostuffIOUtil.mergeFrom(data, t, schema);
            } catch (InstantiationException var5) {
                logger.error("deSerialize error, Class=" + clazz, var5);
            } catch (IllegalAccessException var6) {
                logger.error("deSerialize error, Class=" + clazz, var6);
            } catch (Exception var7) {
                logger.error("deSerialize error, Class=" + clazz, var7);
            }

            return (T) t;
        } else {
            return null;
        }
    }

    private static <T> Schema<? extends T> getSchema(Class<? extends T> clazz) {
        String name = clazz.getName();
        Schema<? extends T> schema = (Schema)schemas.get(name);
        if (schema == null) {
            synchronized(name) {
                schema = (Schema)schemas.get(name);
                if (schema == null) {
                    schema = RuntimeSchema.getSchema(clazz);
                }

                schemas.put(name, schema);
            }
        }

        return schema;
    }

    static {
        for(int i = 0; i < 512; ++i) {
            try {
                linkedBufferPoolQueue.put(LinkedBuffer.allocate(512));
            } catch (InterruptedException var2) {
                logger.error("init linkedBufferQueue error");
            }
        }

    }
}

  1. Kryo序列化方式
package com.example.demo.pro;



import com.alibaba.fastjson.JSONObject;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.minlog.Log;
import com.sf.core.util.KryoFactory;
import com.sf.core.util.KryoTagFactory;
import com.sf.core.util.KryoTagNoRefFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class KryoSerialzeUtil {
    private static final int SPECIAL_BYTE = 0;

    public KryoSerialzeUtil() {
    }

    public static byte[] serialize(Object obj) {
        if (obj == null) {
            return null;
        } else {
            Kryo kryo = null;
            if (obj instanceof JSONObject) {
                kryo = KryoFactory.getDefaultFactory().getKryo();
            } else {
                kryo = KryoTagNoRefFactory.getDefaultFactory().getKryo();
            }

            Output output = null;
            ByteArrayOutputStream os = null;

            byte[] cc;
            try {
                os = new ByteArrayOutputStream();
                output = new Output(os);
                cc = write(obj, kryo, output, os, true);
            } catch (Exception var14) {
                var14.printStackTrace();
                kryo = KryoTagFactory.getDefaultFactory().getKryo();
                os = new ByteArrayOutputStream();
                output = new Output(os);
                cc = write(obj, kryo, output, os, false);
            } finally {
                try {
                    output.close();
                } catch (Exception var13) {
                    cc = null;
                    var13.printStackTrace();
                }

            }

            return cc;
        }
    }

    private static byte[] write(Object obj, Kryo kryo, Output output, ByteArrayOutputStream os, Boolean needNoRef) {
        if (needNoRef) {
            output.write(0);
        }

        kryo.writeObject(output, obj);
        output.flush();
        byte[] b = os.toByteArray();
        return b;
    }

    public static <T> T deSerialize(Class<T> clazz, byte[] bytes) {
        if (bytes != null && bytes.length > 0) {
            ByteArrayInputStream is = null;
            Input input = null;
            T t = null;
            Kryo kryo = null;
            Log.WARN = true;
            boolean isTag = false;

            try {
                byte specialChar;
                if (clazz.getName().equals(JSONObject.class.getName())) {
                    specialChar = bytes[0];
                    if ((specialChar & 255) == 0) {
                        is = new ByteArrayInputStream(bytes, 1, bytes.length);
                    } else {
                        is = new ByteArrayInputStream(bytes);
                    }

                    input = new Input(is);
                    kryo = KryoFactory.getDefaultFactory().getKryo();
                } else {
                    specialChar = bytes[0];
                    if ((specialChar & 255) == 0) {
                        kryo = KryoTagNoRefFactory.getDefaultFactory().getKryo();
                        is = new ByteArrayInputStream(bytes, 1, bytes.length);
                        input = new Input(is);
                    } else {
                        is = new ByteArrayInputStream(bytes);
                        input = new Input(is);
                        byte b = bytes[2];
                        if ((b & 255) == 1) {
                            isTag = true;
                            kryo = KryoTagFactory.getDefaultFactory().getKryo();
                        } else {
                            kryo = KryoFactory.getDefaultFactory().getKryo();
                        }
                    }
                }

                t = kryo.readObject(input, clazz);
            } catch (Exception var19) {
                is = new ByteArrayInputStream(bytes);
                input = new Input(is);
                kryo = switchKryo(clazz, kryo, isTag);
                t = kryo.readObject(input, clazz);
            } catch (Throwable var20) {
                is = new ByteArrayInputStream(bytes);
                input = new Input(is);
                kryo = switchKryo(clazz, kryo, isTag);
                t = kryo.readObject(input, clazz);
            } finally {
                if (is != null) {
                    try {
                        input.close();
                    } catch (Exception var18) {
                        t = null;
                        var18.printStackTrace();
                    }
                }

            }

            return t;
        } else {
            return null;
        }
    }

    private static <T> Kryo switchKryo(Class<T> clazz, Kryo kryo, boolean isTag) {
        if (isTag) {
            kryo = KryoFactory.getDefaultFactory().getKryo();
        } else {
            kryo = KryoTagFactory.getDefaultFactory().getKryo();
        }

        return kryo;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值