Fundamentals of distributed architecture (2) Serialization and deserialization

Serialization and deserialization

Serialization

Serialization: Convert objects into a specific form and then transmit them in the form of a data stream.
Serialization format: XML, Json
Serialization process: Object -> Json -> Transmission (data flow converted from json string)
Serialization purpose: reduce the size of the object, realize cross-platform and cross-language transmission of the object

Deserialization

Deserialization process: Data flow -> Json -> Object

SerializationDemo

服务端:
public static void main (String[] args) {
	
	ServiceSocket serviceSocket = new ServiceSocket(8080);
	Socket socket = serviceSocket.accept();
	
	ObjectInputStream inputStream  = new ObjectInputStream(socket.getInputStream());
	User user = (User)inputStream.readObject();
	……
}
客户端:
public static void main (String args) {
	
	Socket socket = new Socket("localhost", 8080);
	ObjectOutputStream outputStream = new ObjectOutinputStream(socket.getOutputStream());
	User user = new User();
	user.setName("Tom");
	outputStream.writer(user);
	outputStream.flush();
}
对象:
public class User implements Serializable {
	
	private String name:
	public void setName(String name) {
		this.name = name;
	}
	public String getName(){
		return name;
	}
}

Serialization and deserialization in Java

SerializableDemo

Serializable接口:
public instance ISerializable {
	
	//序列化
	<T> byte[] serialize(T object);
	
	//反序列化
	<T> T deSerialize(byte[] data);
}
Serializable接口的实现类:
public class JavaSerialize implements ISerializable {
	
	@Override
	public <T> byte[] serialize (T object) {
		
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		
		try {
			ObjectOutputStream outputStream = new ObjectOutputStream(byteArrayOutputStream);
			outputStream.writerObject(objject);
			return byteArrayOutPutStream.toByteArrray();
		} catch (Execption e) {
			e.printStackTrace();
		}

		 return new byte[0];
	}

	@Override
	public <T> T deSerialize (byte[] data) {
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputSteam(data);
		try{
                ObjectInputStream objectInputStream = new ObjectInputSteam(byteArrayInputStream);
                return (T)objectInputStream.readObject();
            } catch(Exception e) {
                e.printStackTrace();
            }
           return null;
	} 
}
Serializable测试:

public static void main(String[] args) {
	User user = new User();
	user.setName("Tom");

	//将User进行序列化
    ISerializer serializer = new JavaSerializer();
    byte[] bytes = serializer.serialize(user);
    
    //反序列化
    User userRever = serializer.deSerialize(bytes);
}

serialVersionUID

Used to ensure compatibility between class serialization and deserialization. If the two values ​​are different during serialization and deserialization, serialization will fail.

Three situations in which serialVersionUID changes:

  1. Manual modification causes the current serialVersionUID to be different from the one before serialization.
  2. We have not manually written this serialVersionUID constant at all, so the JVM will internally calculate the serialVersionUID value based on the class structure. When the class structure changes (attributes are added, deleted, or the type is modified), this will also cause the serialVersionUID to change.
  3. If the class structure has not changed and serialVersionUID is not defined, but the virtual machines for deserialization and serialization operations are different, it may also cause the calculated serialVersionUID to be different.

transient

The modified fields are not serialized. When writeObjcet\readObject is rewritten, the fields can be serialized. (Similar to hook method)

public class User{
    
    private String name;
    
    private transient int age;
    
    private void wirteObject(ObjectOutputStream out){
        out.defaultWriteObjcet();
        out.writeInt(age);
    }
    
    private void readObject(ObjcetInputStream in) {
		in.defaultReadObjcet();
        age = in.readInt();
    }
}

Serialization technology under distributed architecture

  • XML serialization framework: XStream and Java’s own XML
  • JSON serialization framework: serialization efficiency is very fast (conversion efficiency and transmission efficiency)
  • hessian serialization framework: performance, ease of use, better than the default serialization method
  • dubbo -> hession2
  • Avro serialization
  • kyro serialization framework
  • Protobuf serialization framework

Selection suggestions

  1. For scenarios with low performance requirements, the XML-based SOAP protocol can be used
  2. For scenarios with relatively high requirements on performance and indirection, Hessian, Protobuf, Thrift, and Avro are all suitable.
  3. Based on the separation of front and back ends, or independent external API services, it is better to choose JSON, which is very
    good for debugging and readability.
  4. The design concept of Avro is biased toward dynamically typed languages, so it is okay to use Avro in such scenarios.

Guess you like

Origin blog.csdn.net/baidu_41934937/article/details/114583153