1.需求
1)了解Dubbo的序列化
2)了解Dubbo序列化多种序列化方式源码
2.源码
Serialize
Serialize是Dubbo的核心接口。将对象转成字节流。用于网络传输,以及将字节流转为对象,用于在收到字节流数据后还原成对象。
接口图
1.序列化接口
@SPI("hessian2") public interface Serialization { /** * get content type id * * @return content type id */ byte getContentTypeId(); /** * get content type * * @return content type */ String getContentType(); /** * create serializer * * @param url * @param output * @return serializer * @throws IOException */ @Adaptive ObjectOutput serialize(URL url, OutputStream output) throws IOException; /** * create deserializer * * @param url * @param input * @return deserializer * @throws IOException */ @Adaptive ObjectInput deserialize(URL url, InputStream input) throws IOException; }
SPI注解指定默认实现为hessian2
由于序列化依赖于jdk的OutputStream和InputStream
Dubbo定义了DataOutput DataInput作为各种序列化的输出 输入接口
2.序列化方式
NativeJavaSerialization : Java自带的序列化实现
CompactedJavaSerialization : 压缩java序列化,主要是在原生java序列化基础上,实现了自己定义的类描写叙述符写入和读取
写Object类型的类描写叙述符仅仅写入类名称,而不是类的完整信息。这样有非常多Object类型的情况下能够降低序列化后的size
JavaSerialization : 仅仅是对原生java序列化和压缩java序列化的封装
JsonSerialization : 自己实现的JSON序列化实现
FastJsonSerialization : 使用阿里的FastJson实现的序列化
Hessian2Serialization:使用Hessian2的IO机制实现的序列化(默认实现)
DubboSerialization:Dubbo自己定义的序列化实现
3.Hessian2Serialization实现
public class Hessian2Serialization implements Serialization { public static final byte ID = 2; public byte getContentTypeId() { return ID; } public String getContentType() { return "x-application/hessian2"; } public ObjectOutput serialize(URL url, OutputStream out) throws IOException { return new Hessian2ObjectOutput(out); } public ObjectInput deserialize(URL url, InputStream is) throws IOException { return new Hessian2ObjectInput(is); } }