序列化:dubbo提供了一系列的序列化反序列化对象工具。
Serialization接口定义
@SPI(
"hessian2")
public
interface Serialization {
byte getContentTypeId();
String getContentType();
@Adaptive
ObjectOutput serialize(URL url,OutputStream output) throws IOException;
@Adaptive
ObjectInput deserialize(URL url,InputStream input) throws IOException;
}
DubboSerialization
contentTypeId=1
contentType="x-application/nativejava"
contentTypeId=2
contentType="x-application/hessian2"
JavaSerialization
contentTypeId=3
contentType= "x-application/java"
CompactedJavaSerialization
contentTypeId=4
contentType="x-application/compactedjava"
JsonSerialization
contentTypeId=5
contentType= "text/json"
FastJsonSerialization
contentTypeId=6
contentType= "text/json"
NativeJavaSerialization
contentTypeId=7
contentType= "x-application/nativejava"
SPI注解指定了序列化的默认实现为hessian2
Serialization依赖于jdk的OutputStream,InputStream,因为各具体的序列化工具依赖于OutputStream,InputStream。又为了屏蔽各个序列化接口对dubbo侵入dubbo定义统一的DataOutput DataInput接口来适配各种序列化工具的输入输出
我们拿默认的序列化Hessian2Serialization来举例来说明
public
class Hessian2Serialization implements Serialization{
public ObjectOutput serialize(URLurl, OutputStream out)throws IOException {
return
new Hessian2ObjectOutput(out);
}
public ObjectInput deserialize(URLurl, InputStream is)throws IOException {
return
new Hessian2ObjectInput(is);
}
}
Hessian2Serialization构建基于Hessian的Dubbo 接口Output,Input实现, Dubbo是基于Output, Input接口操作不需要关心具体的序列化反序列化实现方式。
public
class Hessian2ObjectOutput implements ObjectOutput{
private
final Hessian2Output
mH2o; //构建hessian操作类
public Hessian2ObjectOutput(OutputStream os) {
mH2o = new Hessian2Output(os);
mH2o.setSerializerFactory(Hessian2SerializerFactory.SERIALIZER_FACTORY);
}
public
void writeObject(Object obj) throws IOException{
mH2o.writeObject(obj); //利用Hessian序列化对象
}
public
void writeInt(short v)throws IOException {
mH2o.writeInt(v); //利用Hessian序列化int类型
}
…… //为了篇幅省略类似操作
}
Hessian2ObjectInput读取Hessian序列化的数据使用方式同上面类似就不在堆代码了请自己翻看源代码