序列化之Hessian序列化
程序员文章站
2024-03-24 11:54:46
...
Hessian序列化
上一张内容,序列化之JAVA原生序列化
直接上代码了
public class HessianSerializerUtil {
public static <T> byte[] serialize(T obj) {
byte[] bytes = null;
// 1、创建字节输出流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// 2、对字节数组流进行再次封装
// step 1. 定义外部序列化工厂
//ExtSerializerFactory extSerializerFactory = new ExtSerializerFactory();
//extSerializerFactory.addSerializer(java.time.OffsetDateTime.class, new OffsetDateTimeRedisSerializer());
//extSerializerFactory.addDeserializer(java.time.OffsetDateTime.class, new OffsetDateTimeRedisDeserializer());
// step 2. 序列化工厂
//SerializerFactory serializerFactory = new SerializerFactory();
//serializerFactory.addFactory(extSerializerFactory);
HessianOutput hessianOutput = new HessianOutput(bos);
//hessianOutput.setSerializerFactory(serializerFactory);
try {
// 注意,obj 必须实现Serializable接口
hessianOutput.writeObject(obj);
bytes = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
public static <T> T deserialize(byte[] data) {
if (data == null) {
return null;
}
// 1、将字节数组转换成字节输入流
ByteArrayInputStream bis = new ByteArrayInputStream(data);
// step 1. 定义外部序列化工厂
//ExtSerializerFactory extSerializerFactory = new ExtSerializerFactory();
//extSerializerFactory.addSerializer(java.time.OffsetDateTime.class, new OffsetDateTimeRedisSerializer());
//extSerializerFactory.addDeserializer(java.time.OffsetDateTime.class, new OffsetDateTimeRedisDeserializer());
// step 2. 序列化工厂
//SerializerFactory serializerFactory = new SerializerFactory();
//serializerFactory.addFactory(extSerializerFactory);
HessianInput hessianInput = new HessianInput(bis);
//hessianInput.setSerializerFactory(serializerFactory);
Object object = null;
try {
object = hessianInput.readObject();
} catch (IOException e) {
e.printStackTrace();
}
return (T) object;
}
}
pom依赖
<dependency>
<groupId>com.caucho</groupId>
<artifactId>hessian</artifactId>
<version>4.0.38</version>
</dependency>
不过这个序列化不支持OffsetDateTime类型属性
- 序列化效率高于java原生,字节为java原生的一半
下一章来讲protostuff序列化
上一篇: 对代码的简洁优化
下一篇: KVO 的代码简洁使用