Dubbo的版本是基于2.7.3.Release. Dubbo内部的序列化默认实现是用hessian2的序列化框架实现,同时叶预留SPI的扩展点给开发者去实现.下面就来看下-Serialization的api的设计.
/**
* Serialization strategy interface that specifies a serializer. (SPI, Singleton, ThreadSafe)
* The default extension is hessian2 and the default serialization implementation of the dubbo protocol.
@SPI("hessian2")
public interface Serialization {
/**
* Get content type unique id, recommended that custom implementations use values greater than 20.
*/
byte getContentTypeId();
/**
* 获取内容的类型
*/
String getContentType();
/**
* Get a serialization implementation instance
* 序列化
*/
@Adaptive
ObjectOutput serialize(URL url, OutputStream output) throws IOException;
/**
* Get a deserialization implementation instance
* 反序列化的
*/
@Adaptive
ObjectInput deserialize(URL url, InputStream input) throws IOException;
}
Hession实现层就是实现了`Serialization的接口. 实现也比较简单,序列化和反序列化都是 直接new了一个Hession2ObjectOutput和Hession2ObjectInpout对象.
*/
public class Hessian2Serialization implements Serialization {
@Override
public byte getContentTypeId() {
return HESSIAN2_SERIALIZATION_ID;
}
@Override
public String getContentType() {
return "x-application/hessian2";
}
//序列化方法
@Override
public ObjectOutput serialize(URL url, OutputStream out) throws IOException {
return new Hessian2ObjectOutput(out);
}
//反序列化
@Override
public ObjectInput deserialize(URL url, InputStream is) throws IOException {
return new Hessian2ObjectInput(is);
}
}
Duobb框架内部实现的序列化组件的主要是以下9种:
| 序列化框架 | 描述 |
|---|---|
| avro | appache开源的序列化框架 |
| fastjson | 阿里的json的序列化 |
| gson | 谷歌开源的序列化工具 |
| hession2 | dubbo默认使用 |
| jdk | jdk自身的序列化 |
| kryo | Qualcomm Technologies推出的序列化 |
| protobuf-json | protobuf-json是protobuf转json的框架 |
| protobuf | protobuf是谷歌推出的序列化 |
| fst | java快速序列化框架 |
测试用例
protected URL url = new URL("protocol", "1.1.1.1", 1234);
protected ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
@Test
public void test_boolArray_withType() throws Exception {
boolean[] data = new boolean[]{true, false, true};
ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
objectOutput.writeObject(data);
objectOutput.flushBuffer();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
byteArrayOutputStream.toByteArray());
ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream);
assertTrue(Arrays.equals(data, (boolean[]) deserialize.readObject(boolean[].class)));
try {
deserialize.readObject(boolean[].class);
fail();
} catch (ArrayIndexOutOfBoundsException e) {
}
// NOTE: Hessian2 throws ArrayIndexOutOfBoundsException instead of IOException, let's live with this.
}
总结: 今天主要了解下dubbo内部实现了序列化集成的8中组件,后面对于dubboCodec中怎么应用序列化的着重分析.