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);
} }
使用方法场景,及注意事项
使用方法:
实现Delegage接口,并在IdStrategy策略类中注册该Delegate。
使用场景:
当需要序列化的类的字段中有transient声明序列化时会过滤字段,导致还原时丢失信息的场景,或者一些需要高度自定义数据格式的场景下,可以使用Delegate来序列化与反序列化。
注意事项:
这个对象必须是另一个对象的字段时,这个Delegate才会生效,如果直接用Timestamp来转换,则还是不生效,这个问题与源码的实现有关,源码是检测对象的字段来调用Delegate的,如果本身直接过来序列化的时候,则不会触发Delegate。
Protostuff自定义序列化(Delegate)解析的更多相关文章
- Spring源码学习-容器BeanFactory(四) BeanDefinition的创建-自定义标签的解析.md
写在前面 上文Spring源码学习-容器BeanFactory(三) BeanDefinition的创建-解析Spring的默认标签对Spring默认标签的解析做了详解,在xml元素的解析中,Spri ...
- Spring 系列教程之自定义标签的解析
Spring 系列教程之自定义标签的解析 在之前的章节中,我们提到了在 Spring 中存在默认标签与自定义标签两种,而在上一章节中我们分析了 Spring 中对默认标签的解析过程,相信大家一定已经有 ...
- fastjson自定义序列化竟然有这么多姿势?
本文介绍下fastjson自定义序列化的各种操作. 一.什么是fastjson? fastjson是阿里巴巴的开源JSON解析库,它可以解析JSON格式的字符串,支持将Java Bean序列化为JSO ...
- Spring源码阅读笔记05:自定义xml标签解析
在上篇文章中,提到了在Spring中存在默认标签与自定义标签两种,并且详细分析了默认标签的解析,本文就来分析自定义标签的解析,像Spring中的AOP就是通过自定义标签来进行配置的,这里也是为后面学习 ...
- Java程序员必备:序列化全方位解析
前言 相信大家日常开发中,经常看到Java对象"implements Serializable".那么,它到底有什么用呢?本文从以下几个角度来解析序列这一块知识点~ 什么是Java ...
- Hive中自定义序列化器(带编码)
hive SerDe的简介 https://www.jianshu.com/p/afee9acba686 问题 数据文件为文本文件,每一行为固定格式,每一列的长度都是定长或是有限制范围,考虑采用hiv ...
- .Net Core 自定义序列化格式
序列化对大家来说应该都不陌生,特别是现在大量使用WEBAPI,JSON满天飞,序列化操作应该经常出现在我们的代码上. 而我们最常用的序列化工具应该就是Newtonsoft.Json,当然你用其它工具类 ...
- Android之XML序列化和解析
XML文件是一种常用的文件格式,可以用来存储与传递数据 ,本文是XML文件序列化与解析的一个简单示例 写文件到本地,并用XML格式存储 /** * 写xml文件到本地 */ private void ...
- Newtonsoft.Json高级用法 1.忽略某些属性 2.默认值的处理 3.空值的处理 4.支持非公共成员 5.日期处理 6.自定义序列化的字段名称
手机端应用讲究速度快,体验好.刚好手头上的一个项目服务端接口有性能问题,需要进行优化.在接口多次修改中,实体添加了很多字段用于中间计算或者存储,然后最终用Newtonsoft.Json进行序列化返回数 ...
随机推荐
- win平台下, 检测网络是否连接最好的办法
[Delphi]检查URL是否有效的函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 function CheckUr ...
- jdbc.properties 包含多种数据库驱动链接的版本。
# Properties file with JDBC-related settings. ########## # HSQLDB # ########## #jdbc.driverClassName ...
- 查看 AndroidManifest.xml文件
1.Manifest Explorer 装在Android手机中,用此apk看系统中已安装应用的AndroidManifest.xml文件: protected boolean configForPa ...
- Asp.Net Mvc后台数据验证自测小Demo
使用过MVC的同学一定不陌生MVC的模型绑定和模型校验,使用起来非常方便,定义好Entity之后,在需要进行校验的地方可以打上相应的Attribute,在Action开始时检查ModelState的I ...
- 【Java】Java8新增的Lambda表达式_学习笔记
一.Lambda表达式可以简化创建匿名内部类对象 1.不需要new XXX(){}这种繁琐代码. 2.不需要指出重写的方法名. 3.不要给出重写的方法的返回值类型. 4.Lambda相当于一个匿名方法 ...
- motan源码分析十一:部分特性
本章将描述motan部分的特性并对源码进行分析. 1.requestid的维护,使用了当前时间左移20位,再和一个自增变量组合 public class RequestIdGenerator { ); ...
- Java 获取今天之前的七天 的日期
package test; import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date; pub ...
- XCODE 代码行统计
find . -name "*.m" -or -name "*.h" -or -name "*.c" |xargs grep -v &quo ...
- Android ExpandableListView实例Demo
前几篇文章介绍了Listview.但在实际开发中也常常会用到多层的Listview来展示数据,比方qq中的好友展示,所以这张来了解一下ExpandableListview.基本思想与Listview大 ...
- [转] C语言多维数组与多级指针
http://c.biancheng.net/cpp/html/477.html 多维数组与多级指针也是初学者感觉迷糊的一个地方.超过二维的数组和超过二级的指针其实并不多用.如果能弄明白二维数组与二级 ...