背景

在使用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. linux内核空间与用户空间信息交互方法

    linux内核空间与用户空间信息交互方法     本文作者: 康华:计算机硕士,主要从事Linux操作系统内核.Linux技术标准.计算机安全.软件测试等领域的研究与开发工作,现就职于信息产业部软件与 ...

  2. 【Gzip】

    为你的网站开启 gzip 压缩功能(nodejs.nginx) Do not forget to use Gzip for Express.js 网页GZIP压缩检测

  3. 【贪心】Vijos P1615 旅行

    题目链接: https://vijos.org/p/1615 题目大意: N条路,路的高度给你,走一条路的耗费体力是从上一条路的高度到当前路高度的绝对值差. 可以改变一条路的高度,耗费的体力等于改变前 ...

  4. iOS: 关于Certificate、Provisioning Profile、App ID的介绍及其之间的关系

    刚接触iOS开发的人难免会对苹果的各种证书.配置文件等不甚了解,可能你按照网上的教程一步一步的成功申请了真机调试,但是还是对其中的缘由一知半解.这篇文章就对Certificate.Provisioni ...

  5. 【模拟赛】BYVoid魔兽世界模拟赛 解题报告

    题目名称(点击进入相关题解) 血色先锋军 灵魂分流药剂 地铁重组 埃雷萨拉斯寻宝 源文件名(.c/.cpp/.pas) scarlet soultap subway eldrethalas 输入文件名 ...

  6. angularJS 过滤器 表单验证

    过滤器1.filter的作用就是接收一个输入,通过某个规则进行处理,然后返回处理后的结果,主要用于数据的格式化.2.内置过滤器(1)Currency(货币)将一个数值格式化为货币格式,默认为$(2)D ...

  7. Solr使用solr4J操作索引库

    Solrj是Solr搜索服务器的一个比较基础的客户端工具,可以非常方便地与Solr搜索服务器进行交互.最基本的功能就是管理Solr索引,包括添加.更新.删除和查询等.对于一些比较基础的应用,用Solj ...

  8. php开启curl和openssl

    php开启curl和openssl 开启php curl函数库的步骤 1).去掉windows/php.ini 文件里;extension=php_curl.dll前面的; /*用 echo phpi ...

  9. 【每日一linux命令8】添加新的工作组(groupadd)

    groupadd (字意add group)增加一个新的工作组. 语法:groupadd 选项 用户组名 选项: -g 指定新建工作组的ID -r 创建系统工作组,系统工作组的ID小于500 -k 覆 ...

  10. lesson10:hashmap变慢原因分析

    下面的英文描述了String.hashCode()方法,在特定情况下,返回值为0的问题: Java offers the HashMap and Hashtable classes, which us ...