Serialization and Deserialization

Distributed interface technology: webService, RMI, Ali json, Google msgpack

Definition:
Serillization serialization is a process in which an object generates a series of characters according to certain rules.
Deserialization Deserialization is a process of rebuilding these characters into an in-memory object.

Scenario:
When saving an in-memory object to a file or database (persistence).
When you need to transfer objects over the network in a cross-platform environment (webService soap).
When you transfer objects via RMI.

Implementation method:
The class to be serialized implements the Serializable interface.
Serializable doesn't have any methods, just a marker that this class can be instantiated.

Example:
java default serialization rules:
package org.xdemo.example.SpringActivemq.service.consumer;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerialTest {

	public static void main(String[] args) throws ClassNotFoundException {
		
		String stuFileName = "student.out";
		
		Student serialStu = new Student("海龙", 11);
		serialize(serialStu, stuFileName);
		
		Student student = (Student)deserialize(stuFileName);
		System.out.println("name:" + student.getName() + ",age:"+ student.getAge());
		
	}

	/**
	 * Serialization
	 * @param obj
	 * @param outFile
	 */
	public static void serialize(Object obj, String outFile) {
		
		try {
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(outFile));
			
			//Write the state of the current in-memory object to disk.
			oos.writeObject (obj);
			// clear
			oos.flush ();
			//closure
			oos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}
	}

	/**
	 * deserialize
	 * @param obj
	 * @param outFile
	 * @throws ClassNotFoundException
	 */
	public static Object deserialize(String readFile) throws ClassNotFoundException {
		
		ObjectInputStream ois;
		Object object;
		try {
			ois = new ObjectInputStream(new FileInputStream(readFile));
			object = ois.readObject();
			ois.close();
			return object;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}
		return null;
	}
}


package org.xdemo.example.SpringActivemq.service.consumer;

import java.io.Serializable;

public class Student implements Serializable{

	private String name;
	// transient static
	private int age;
	
	public Student(String name, int age) {
		this.name = name;
		this.age = 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;
//	}
	
	//jdk automatically calls, extends the method of serialization rules.
//	private void writeObject(ObjectOutputStream out) throws IOException{
//		out.defaultWriteObject();
//		out.writeInt(age);
//	}
//	
//	private void readObject(ObjectInputStream in) throws IOException,ClassNotFoundException{
//		in.defaultReadObject();
//		age = in.readInt();
//	}
}


Serialization IDs for serialization and deserialization need to be the same.
Therefore, the serialized ID is set consistently across platforms and services.

If we want to serialize an object, first create an OutPutStream (such as FileOutPutStream, etc.);
at this time, we only need to directly call the writeObject() method to instantiate the object and send it to the OutputStream for
serialization based on bytes, without using Reader and Writer based on character level IO.

For deserialization (restore a sequence into an object), you need to encapsulate an InputStream in ObjectInputStream.
Then call readObject.

Affect serialization:
1 Plus transient can not be serialized, for sensitive information do not serialize.
2 It is modified by static static variables and cannot be serialized.
3 Override the writeObject method and the readObject method.
4 Implement the interface Externalizable (normally implement the interface Serializable)
jdk will not call the default serialization interface, use custom writeExternal and readExternal
5. Use readResolve(): When we use the singleton pattern, we should expect this class instance to be unique.
But the class is serializable, so the situation may be different. In this case, the readResolve method can be added to
ensure that there is only one reference to a singleton object in the same jvm.

Two data types, reference type, value type.
== Whether the reference address is the same Shallow clone After serialization and deserialization == is false
equals Whether the ratio is the same For example, the string content is deep cloned and equals is true after serialization and deserialization Serialization

under the network:
1.java Environment RMI (Remote Method Invoker) is limited to the java platform
, and the serialization efficiency is low 2. webServer
SOAP simple object outgoing protocol ) Cross-language and cross-platform Strong readability and serialization efficiency has been improved, but the efficiency is not the highest Alibaba's fastjson1.2.4.jar






//Serialization
String json = JSON.toJSONString(msgPack);
// {"age":8,"name":"Sea Dragon"} key-value pair storage size is larger than msgPack
// msgPack is org.xdemo.example.SpringActivemq.service.consumer.MsgPack@69ac44c2
System.out.println(json);
// deserialize
MsgPack msgPack3 =  JSON.parseObject(json, MsgPack.class);
System.out.println("name:" + msgPack3.name + ",age:"+ msgPack3.age + "_json");


<!-- Alibaba https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.4</version>
</dependency>


4. The new serial library MessagePack (Google)
has high efficiency and small files after serialization. Jars are
required : msgpack-0.6.12.jar, javassist-3.18.2-GA.jar

	 
<!-- Serialize msgpack -->
		<!-- https://mvnrepository.com/artifact/org.msgpack/msgpack -->
		<dependency>
		    <groupId>org.msgpack</groupId>
		    <artifactId>msgpack</artifactId>
		    <version>0.6.12</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
		<dependency>
		    <groupId>org.javassist</groupId>
		    <artifactId>javassist</artifactId>
		    <version>3.18.1-GA</version>
		</dependency>




	    
MsgPack msgPack = new MsgPack();
msgPack.name = "Sea Dragon";
msgPack.age= 8;
try {
	    	// Serialization
			byte[] arr = MessagePack.pack(msgPack);
			// deserialize
			MsgPack msgPack2 =  MessagePack.unpack(arr, MsgPack.class);
			System.out.println("name:" + msgPack2.name + ",age:"+ msgPack2.age + "_msgPack");
			System.out.println(msgPack == msgPack2);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}


package org.xdemo.example.SpringActivemq.service.consumer;

import org.msgpack.annotation.Message;

//redis2.6 also supports MsgPack
@Message
public class MsgPack {

	public String name;
	
	public int age;
}


// use this method to test the time
long msgpackStart = System.currentTimeMillis();
long msgpackEnd = System.currentTimeMillis();
System.out.println(msgpackEnd - msgpackStart);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326726029&siteId=291194637