一、好句:
枯燥的日子,將心漸漸磨出了平靜,于是,學會了習慣,也學會了把握。人生就是一場匆忙的路過,優雅不失訓練出來的,而是一種人生閱歷。
二、背景
這篇是之前考慮序列化的問題想得,那么在分布式里面如果通過序列化傳輸,兩邊的serId不一致,如果還使用jdk的序列化方式怎么可以解析的成功了?
三、hessian方式
1.參數及返回值需實現Serializable接口
2.參數及返回值不能自定義實現List, Map, Number, Date, Calendar等接口,只能用JDK自帶的實現,因為hessian會做特殊處理,自定義實現類中的屬性值都會丟失。()
3.Hessian序列化,只傳成員屬性值和值的類型,不傳方法或靜態變量,兼容情況:(由吳亞軍提供)
Paste_Image.png
其實在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 + "]";
}
}