一、好句:
枯燥的日子,将心渐渐磨出了平静,于是,学会了习惯,也学会了把握。人生就是一场匆忙的路过,优雅不失训练出来的,而是一种人生阅历。
二、背景
这篇是之前考虑序列化的问题想得,那么在分布式里面如果通过序列化传输,两边的serId不一致,如果还使用jdk的序列化方式怎么可以解析的成功了?
三、hessian方式
1.参数及返回值需实现Serializable接口
2.参数及返回值不能自定义实现List, Map, Number, Date, Calendar等接口,只能用JDK自带的实现,因为hessian会做特殊处理,自定义实现类中的属性值都会丢失。()
3.Hessian序列化,只传成员属性值和值的类型,不传方法或静态变量,兼容情况:(由吴亚军提供)
其实在dubbo分布式中,序列化传输使用的hessian方式进行序列化
<!-- https://mvnrepository.com/artifact/com.caucho/hessian -->
<dependency>
<groupId>com.caucho</groupId>
<artifactId>hessian</artifactId>
<version>4.0.38</version>
</dependency>
或者引入dubbo的包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.8.4</version>
</dependency>
相关测试代码如下:
package com.mouse.moon.hessian;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import com.alibaba.com.caucho.hessian.io.HessianSerializerInput;
import com.alibaba.com.caucho.hessian.io.HessianSerializerOutput;
import com.mouse.moon.serializable.Student;
/**
*
* @author Mahone Wu
* @Date:2017-02-28
*/
public class SerializeHessian {
public static void main(String args[]){
Student student = new Student();
student.setAge(10);
student.setName("123");
student.setName("深圳");
byte[] results = null;
ByteArrayOutputStream os = null;
HessianSerializerOutput hessianOut = null;
ByteArrayInputStream is = null;
Student serStu = null;
try{
//进行序列化操作
os = new ByteArrayOutputStream();
hessianOut = new HessianSerializerOutput(os);
hessianOut.writeObject(student);
os.close();
results = os.toByteArray();
System.out.println(results);
//反序列化操作
is = new ByteArrayInputStream(results);
HessianSerializerInput hessianInput = new HessianSerializerInput(is);
serStu = (Student)hessianInput.readObject();
System.out.println("-------反序列化数据----"+serStu);
}catch(Exception e){
e.printStackTrace();
}
}
}
package com.mouse.moon.serializable;
import java.io.Serializable;
public class Student implements Serializable{
private String name;
private int age;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", address="
+ address + "]";
}
}