在现在这个微服务横行的年代远程调用越来越多,服务器之间相互通信靠的就是一个字:对象序列化!
那么究竟什么叫做对象序列化呢?
我们都知道对象是放在java虚拟机(JVM)中,所以对象的生命周期不可能比虚拟机生命周期长,如果要打破这个规则怎么办?答:将处在java虚拟机中的对象持久化到磁盘中,到使用的时候再将磁盘上的文件拿到按照一定的策略反向生成对象并加载到java虚拟机中。
提炼一下上面的话:
- 序列化:将处在JVM中的对象持久化到文件中(文件可以是磁盘,可以是网络也可以是另一个虚拟机)
- 反序列化:将文件中的对象重新加载到JVM的过程。
先来看一个简单例子看一下序列化
package test;
import java.io.Serializable;
/**
* @Author: chao.zhu
* @description: 这是一个最简单的实体类,实现Serializable
* @CreateDate: 2018/12/28
* @Version: 1.0
*/
public class Person implements Serializable {
//注意:这里我没有重写serialVersionUID
private String name;
private int age;
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;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
上面实体类是即将序列化的类,注意这个我没有写serialVersionUID。主要是想描述serialVersionUID的作用。
public class JdkSerializable {
public static void main(String[] args) throws Exception {
enSerializeable();
deSerializeable();
}
public static void enSerializeable() throws Exception {
Person person = new Person();
person.setAge(10);
person.setName("abc");
ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream("person"));
oo.writeObject(person);
}
public static void deSerializeable() throws Exception{
ObjectInputStream oi = new ObjectInputStream(new FileInputStream("person"));
Person person = (Person) oi.readObject();
System.out.println(person.toString());
}
}
上面将person对象进行序列化,和反序列化得到person对象并输出。下面我们在Person里面增加一个sex属性:
public class Person implements Serializable {
private String name;
private int age;
private String sex;
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
然后在main方法里面只执行deSerializeable()
方法可以看到报错
public class JdkSerializable {
public static void main(String[] args) throws Exception {
// enSerializeable();
deSerializeable();
}
public static void enSerializeable() throws Exception {
Person person = new Person();
person.setAge(10);
person.setName("abc");
ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream("person"));
oo.writeObject(person);
}
public static void deSerializeable() throws Exception{
ObjectInputStream oi = new ObjectInputStream(new FileInputStream("person"));
Person person = (Person) oi.readObject();
System.out.println(person.toString());
}
}
报错信息如下:
/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/bin/java "-javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=52245:/Applications/IntelliJ IDEA.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/lib/ant-javafx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/lib/dt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/lib/javafx-mx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/lib/jconsole.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/lib/packager.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/lib/sa-jdi.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/lib/tools.jar:/Users/zhuchao/workspace_my_git/cjxz_parent/serialization_test/target/classes test.JdkSerializable
objc[1379]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/bin/java (0x10c4bb4c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x10d4d44e0). One of the two will be used. Which one is undefined.
Exception in thread "main" java.io.InvalidClassException: test.Person; local class incompatible: stream classdesc serialVersionUID = 1567747183838728854, local class serialVersionUID = 3380613134262651561
at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:616)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1843)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1713)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2000)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
at test.JdkSerializable.deSerializeable(JdkSerializable.java:34)
at test.JdkSerializable.main(JdkSerializable.java:20)
Process finished with exit code 1
看上面的异常信息是说两次序列化的serialVersionUID不同。如果我们在Person类中增加serialVersionUID这个值,然后在进行上面的操作会发现不报错了。这就是serialVersionUID的作用。
当序列化对象的时候如何没有serialVersionUID,JAVA虚拟机会通过类里面的属性,方法通过摘要算法得到一个serialVersionUID。然后在反序列化的时候会判断对象的serialVersionUID和类里面的serialVersionUID是否相同,如果不同则抛出异常。但如果我们重写了serialVersionUID。那么序列化时serialVersionUID已经确定,这是如果类里面增加属性或者方法只要serialVersionUID不变,那么反序列化是对象里面的serialVersionUID和类里面的serialVersionUID相同,这样就不会出错了。
现在终于知道为什么我们在开发的时候需要重写serialVersionUID了吧,如果不重写会导致我们修改类之后原来持久化的对象无法转化成修改后的类!
在提几个边角问题?
- 序列化时静态变量会被序列化吗?
- 答:不会,因为静态变量是类的属性,不是对象。序列化是将对象序列化到文件
- 序列化对象时,
writeObject(person);
执行两次文件大小是如何变化的? - 答:不是累加,在这里JDK序列化做了优化,将文件引用*2即可
-
transient String sex;
transient的作用? - 答:在序列化对象时,会忽略这个属性
- 父类没有实现
Serializable
接口子类实现了,再序列化时会序列化父类的属性吗? - 答:不会
常见的其他序列化框架
protobuf
这是google提供的一个序列化框架跨平台
JSON
json可以使用阿里提供的FastJson将对象转成json字符串在网络中传输。比较简单学习成本也比较低人眼就可以阅读
kryo
下面是kryo最简单的demo
import java.beans.Transient;
import java.io.Serializable;
/**
* @Author: chao.zhu
* @description:
* @CreateDate: 2018/12/28
* @Version: 1.0
*/
public class Person2 {
private String name;
private int age;
transient String sex;
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;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
package test;
import java.io.FileOutputStream;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
/**
* @Author: chao.zhu
* @description:
* @CreateDate: 2018/12/28
* @Version: 1.0
*/
public class KryoSerializable {
public static void main(String[] args)throws Exception {
enSerializable();
}
public static void enSerializable()throws Exception{
//创建对象
Person2 person2 = new Person2();
person2.setAge(10);
person2.setName("123");
//序列化成byte数组
Kryo kryo = new Kryo();
Output output = new Output(1024);
kryo.writeObject(output,person2);
byte[] bytes = output.toBytes();
System.out.println(new String(bytes));
System.out.println(bytes.length);
//反序列化
Input input = new Input(bytes);
Kryo kryo1 = new Kryo();
Person2 p = kryo1.readObject(input,Person2.class);
System.out.println(p.toString());
}
}
thrift
demo就不写了
小结
对象系列化就是将内存中的对象转换成字节码数组然后在网络中传播,或者持久化到磁盘。为什么有的序列化效率高并且系列化结果小,有的有不行呢?这是因为序列化其实也是一种定义规则的过程。你想如果我们规定系列化时所有的字段名称都是只记录值,不保存对象的信息,这样在反序列化时可以直接使用反序列化传递的class进行解析。这样不就在传递过程中数据量就小了很多嘛