22. Dubbo原理解析-编码解码之Serialization接口定义

序列化: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"

 

Hessian2Serialization

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序列化的数据使用方式同上面类似就不在堆代码了请自己翻看源代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值