• Protostuff自定义序列化(Delegate)解析


    背景
    在使用Protostuff进行序列化的时候,不幸地遇到了一个问题,就是Timestamp作为字段的时候,转换出现问题,通过Protostuff转换后的结果都是1970-01-01 08:00:00,这就造成了Timestamp不能够序列化。于是Google了一番,得知可以用Delegate来解决这个问题。

    原来的代码
    ProtobufferCodec类

    import java.lang.reflect.Constructor;
    import java.util.Map;
    import java.util.concurrent.ConcurrentHashMap;

    import io.protostuff.LinkedBuffer;
    import io.protostuff.ProtostuffIOUtil;
    import io.protostuff.Schema;
    import io.protostuff.runtime.RuntimeSchema;

    public class ProtobufferCodec implements Codec {

    private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<>();

    public ProtobufferCodec() {

    }

    @Override
    public short getId() {
    return Codecs.PROTOBUFFER_CODEC;
    }

    @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);
    if (schema != null) {
    cachedSchema.put(cls, schema);
    }
    }
    return schema;
    }

    @Override
    public <T> byte[] encode(T obj) {
    if (obj == null) {
    return null;
    }
    Class<T> cls = (Class<T>) obj.getClass();
    LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
    try {
    Schema<T> schema = getSchema(cls);
    byte[] bytes = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
    return bytes;
    } catch (Exception e) {
    throw new IllegalStateException(e.getMessage(), e);
    } finally {
    buffer.clear();
    }
    }

    @Override
    public <T> T decode(byte[] bytes, Class<T> clazz) {
    if (bytes == null || bytes.length == 0) {
    return null;
    }
    try {
    Constructor<T> constructor = clazz.getConstructor();
    constructor.setAccessible(true);
    T message = constructor.newInstance();
    Schema<T> schema = getSchema(clazz);
    ProtostuffIOUtil.mergeFrom(bytes, message, schema);
    return message;
    } catch (Exception e) {
    throw new IllegalStateException(e.getMessage(), e);
    }
    }

    }
    Codec接口
    /**
    * 编解码器
    * @author jiujie
    * @version $Id: Codec.java, v 0.1 2016年3月31日 上午11:39:14 jiujie Exp $
    */
    public interface Codec {

    /**
    * 编解码器ID,用于标识编解码器
    * @author jiujie
    * 2016年3月31日 上午11:38:39
    * @return
    */
    public short getId();

    /**
    * 把对象数据结构编码成一个DataBuffer
    * @param <T>
    */
    public <T> byte[] encode(T obj);

    /**
    * 把DataBuffer解包构造一个对象
    * @param <T>
    */
    public <T> T decode(byte[] bytes, Class<T> clazz);

    修改后的代码
    import java.sql.Timestamp;
    import java.util.concurrent.ConcurrentHashMap;

    import io.protostuff.LinkedBuffer;
    import io.protostuff.ProtostuffIOUtil;
    import io.protostuff.Schema;
    import io.protostuff.runtime.DefaultIdStrategy;
    import io.protostuff.runtime.Delegate;
    import io.protostuff.runtime.RuntimeEnv;
    import io.protostuff.runtime.RuntimeSchema;

    /**
    * ProtoBuffer编解码
    * @author jiujie
    * @version $Id: ProtobufferCodec.java, v 0.1 2016年7月20日 下午1:52:41 jiujie Exp $
    */
    public class ProtobufferCodec implements Codec {

    /** 时间戳转换Delegate,解决时间戳转换后错误问题 @author jiujie 2016年7月20日 下午1:52:25 */
    private final static Delegate<Timestamp> TIMESTAMP_DELEGATE = new TimestampDelegate();

    private final static DefaultIdStrategy idStrategy = ((DefaultIdStrategy) RuntimeEnv.ID_STRATEGY);

    private final static ConcurrentHashMap<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<>();

    static {
    idStrategy.registerDelegate(TIMESTAMP_DELEGATE);
    }

    public ProtobufferCodec() {
    }

    @Override
    public short getId() {
    return Codecs.PROTOBUFFER_CODEC;
    }

    @SuppressWarnings("unchecked")
    public static <T> Schema<T> getSchema(Class<T> clazz) {
    Schema<T> schema = (Schema<T>) cachedSchema.get(clazz);
    if (schema == null) {
    schema = RuntimeSchema.createFrom(clazz, idStrategy);
    cachedSchema.put(clazz, schema);
    }
    return schema;
    }

    @Override
    public <T> byte[] encode(T obj) {
    if (obj == null) {
    return null;
    }
    @SuppressWarnings("unchecked")
    Class<T> cls = (Class<T>) obj.getClass();
    LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
    try {
    Schema<T> schema = getSchema(cls);
    byte[] bytes = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
    return bytes;
    } catch (Exception e) {
    throw new IllegalStateException(e.getMessage(), e);
    } finally {
    buffer.clear();
    }
    }

    @Override
    public <T> T decode(byte[] bytes, Class<T> clazz) {
    if (bytes == null || bytes.length == 0) {
    return null;
    }
    try {
    Schema<T> schema = getSchema(clazz);
    //改为由Schema来实例化解码对象,没有构造函数也没有问题
    T message = schema.newMessage();
    ProtostuffIOUtil.mergeFrom(bytes, message, schema);
    return message;
    } catch (Exception e) {
    throw new IllegalStateException(e.getMessage(), e);
    }
    }

    }

    TimestampDelegate类

    import java.io.IOException;
    import java.sql.Timestamp;

    import io.protostuff.Input;
    import io.protostuff.Output;
    import io.protostuff.Pipe;
    import io.protostuff.WireFormat.FieldType;
    import io.protostuff.runtime.Delegate;

    /**
    * protostuff timestamp Delegate
    * @author jiujie
    * @version $Id: TimestampDelegate.java, v 0.1 2016年7月20日 下午2:08:11 jiujie Exp $
    */
    public class TimestampDelegate implements Delegate<Timestamp> {

    public FieldType getFieldType() {
    return FieldType.FIXED64;
    }

    public Class<?> typeClass() {
    return Timestamp.class;
    }

    public Timestamp readFrom(Input input) throws IOException {
    return new Timestamp(input.readFixed64());
    }

    public void writeTo(Output output, int number, Timestamp value,
    boolean repeated) throws IOException {
    output.writeFixed64(number, value.getTime(), repeated);
    }

    public void transfer(Pipe pipe, Input input, Output output, int number,
    boolean repeated) throws IOException {
    output.writeFixed64(number, input.readFixed64(), repeated);
    }

    }


    版权声明:本文为CSDN博主「笔下生灰」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/connect_me/article/details/51970201

  • 相关阅读:
    php 高并发
    mysql 基础明细
    关于高并发和秒杀系统,你知道的和不知道的一些事
    carbon
    自定义tarbar
    学习小参考
    lnmp1.4,400,500,错误
    PHPSTORM+Thinkphp3.2模板标签替换Thinkphp5.1公式
    Thinkphp5.1手册太简单,有的功能用起来不确定结果是否和预料的一样,顾整理记录
    CentOS7 最小化安装vmware-tools
  • 原文地址:https://www.cnblogs.com/duanxz/p/4494212.html
Copyright © 2020-2023  润新知