背景

在使用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);
} }

使用方法场景,及注意事项

使用方法:

实现Delegage接口,并在IdStrategy策略类中注册该Delegate。

使用场景:

当需要序列化的类的字段中有transient声明序列化时会过滤字段,导致还原时丢失信息的场景,或者一些需要高度自定义数据格式的场景下,可以使用Delegate来序列化与反序列化。

注意事项:

这个对象必须是另一个对象的字段时,这个Delegate才会生效,如果直接用Timestamp来转换,则还是不生效,这个问题与源码的实现有关,源码是检测对象的字段来调用Delegate的,如果本身直接过来序列化的时候,则不会触发Delegate。

Protostuff自定义序列化(Delegate)解析的更多相关文章

  1. Spring源码学习-容器BeanFactory(四) BeanDefinition的创建-自定义标签的解析.md

    写在前面 上文Spring源码学习-容器BeanFactory(三) BeanDefinition的创建-解析Spring的默认标签对Spring默认标签的解析做了详解,在xml元素的解析中,Spri ...

  2. Spring 系列教程之自定义标签的解析

    Spring 系列教程之自定义标签的解析 在之前的章节中,我们提到了在 Spring 中存在默认标签与自定义标签两种,而在上一章节中我们分析了 Spring 中对默认标签的解析过程,相信大家一定已经有 ...

  3. fastjson自定义序列化竟然有这么多姿势?

    本文介绍下fastjson自定义序列化的各种操作. 一.什么是fastjson? fastjson是阿里巴巴的开源JSON解析库,它可以解析JSON格式的字符串,支持将Java Bean序列化为JSO ...

  4. Spring源码阅读笔记05:自定义xml标签解析

    在上篇文章中,提到了在Spring中存在默认标签与自定义标签两种,并且详细分析了默认标签的解析,本文就来分析自定义标签的解析,像Spring中的AOP就是通过自定义标签来进行配置的,这里也是为后面学习 ...

  5. Java程序员必备:序列化全方位解析

    前言 相信大家日常开发中,经常看到Java对象"implements Serializable".那么,它到底有什么用呢?本文从以下几个角度来解析序列这一块知识点~ 什么是Java ...

  6. Hive中自定义序列化器(带编码)

    hive SerDe的简介 https://www.jianshu.com/p/afee9acba686 问题 数据文件为文本文件,每一行为固定格式,每一列的长度都是定长或是有限制范围,考虑采用hiv ...

  7. .Net Core 自定义序列化格式

    序列化对大家来说应该都不陌生,特别是现在大量使用WEBAPI,JSON满天飞,序列化操作应该经常出现在我们的代码上. 而我们最常用的序列化工具应该就是Newtonsoft.Json,当然你用其它工具类 ...

  8. Android之XML序列化和解析

    XML文件是一种常用的文件格式,可以用来存储与传递数据 ,本文是XML文件序列化与解析的一个简单示例 写文件到本地,并用XML格式存储 /** * 写xml文件到本地 */ private void ...

  9. Newtonsoft.Json高级用法 1.忽略某些属性 2.默认值的处理 3.空值的处理 4.支持非公共成员 5.日期处理 6.自定义序列化的字段名称

    手机端应用讲究速度快,体验好.刚好手头上的一个项目服务端接口有性能问题,需要进行优化.在接口多次修改中,实体添加了很多字段用于中间计算或者存储,然后最终用Newtonsoft.Json进行序列化返回数 ...

随机推荐

  1. Spring基础介绍

    Spring属于轻量级还是重量级框架?   这需针对使用Spring的功能而言,比如我们常使用其核心服务整合SSH,这样则为轻量级. 如果使用其大部分服务则可以理解为重量级.   普通JAVA项目环境 ...

  2. AOP举例子

    切面类TestAspect package com.spring.aop; /** * 切面 * */ public class TestAspect { public void doAfter(Jo ...

  3. Spring MVC学习总结。

    公司项目用的Spring MVC.顺便学习学习. 其实框架并没有想象中的复杂.尤其对于初学者,总觉得SSH是一些很复杂的东西似的.其实对初学者来说能够用这些框架就足够了.在公司里也是,基本功能会用了就 ...

  4. 高效算法——J 中途相遇法,求和

    ---恢复内容开始--- J - 中途相遇法 Time Limit:9000MS     Memory Limit:0KB     64bit IO Format:%lld & %llu Su ...

  5. 更新一波题解(最近做的三个dp题)

    很久没写题解了,去ec之前来填一填坑,希望能攒攒人品... 首先是去年上海F题..uvalive7143 题意: 给n个人分 m间房子,每个房间的容量是已知的,其中有k对双胞胎,双胞胎可以看作相同的人 ...

  6. zoj 3462

    #include <cstdio> #include <cmath> #include <algorithm> #include <iostream> ...

  7. shell timeout

    写脚本的时候,经常需要用到超时控制.看<shell专家编程>时看到一个好例:修改了一下, 1.超过timeout时间还没执行完,则kill进程,发邮件告警: set-xmailSend() ...

  8. runtime 如何实现 weak 属性

    出题者简介: 孙源(sunnyxx),目前就职于百度 整理者简介:陈奕龙(子循),目前就职于滴滴出行. 转载者:豆电雨(starain)微信:doudianyu 要实现 weak 属性,首先要搞清楚 ...

  9. errno与perror

    很多系统函数在错误返回时将错误原因记录在libc定义的全局变量errno中,每种错误原因对应一个错误码,请查阅errno(3)的Man Page了解各种错误码,errno在头文件errno.h中声明, ...

  10. Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.5:clean (default-clean) on project taotao-manager-web: Failed to clean project: Failed to delete \target\tomcat\logs\access_log.201

    点击console右上角叉号然后再点击红色小方形terminate