源码分析Dubbo序列化-源码分析kryo序列化实现原理

本文深入分析了Dubbo中Kryo序列化的实现原理,包括如何处理null对象、对象引用、对象图循环依赖等问题。通过源码解读,阐述了Kryo如何减少序列化后的数据大小以提高性能,如使用变长字节存储和对象引用缓存。同时,文章提到了Kryo与Java序列化的区别,并提供了作者的其他源码分析专栏链接。
摘要由CSDN通过智能技术生成

/** @param object May be null if mayBeNull is true.

  • @return true if no bytes need to be written for the object. */

boolean writeReferenceOrNull (Output output, Object object, boolean mayBeNull) { // @1

if (object == null) { // @2

if (TRACE || (DEBUG && depth == 1)) log(“Write”, null);

output.writeVarInt(Kryo.NULL, true);

return true;

}

if (!referenceResolver.useReferences(object.getClass())) { // @3

if (mayBeNull) output.writeVarInt(Kryo.NOT_NULL, true);

return false;

}

// Determine if this object has already been seen in this object graph.

int id = referenceResolver.getWrittenId(object); // @4

// If not the first time encountered, only write reference ID.

if (id != -1) { // @5

if (DEBUG) debug(“kryo”, "Write object reference " + id + ": " + string(object));

output.writeVarInt(id + 2, true); // + 2 because 0 and 1 are used for NULL and NOT_NULL.

return true;

}

// Otherwise write NOT_NULL and then the object bytes.

id = referenceResolver.addWrittenObject(object); // @6

output.writeVarInt(NOT_NULL, true);

if (TRACE) trace(“kryo”, "Write initial object reference " + id + ": " + string(object));

return false; // @7

}

代码@1:参数说明:Output output:输出流;Object object:待序列化的对象;

代码@2:如果对象为空,写入Kryo.NULL(0),然后返回true,表示需要设置generic,后续会讲解一下generic(泛型支持)。

代码@3:如果是基本类型,如果maybe(值可能为空),但该方法不为空,则设置为Kryo.NOT_NULL,然后返回false,表示非引用类型,需要持久化值。

代码@4:判断该对象是否在对象图中已被序列化一次。(其实现方式ListReferenceResolver、MapReferenceResolver)。

ListReferenceResolver#getWrittenId

public int getWrittenId (Object object) {

for (int i = 0, n = seenObjects.size(); i < n; i++) {

if (seenObjects.get(i) == object) {

return i;

}

}

return -1;

}

代码@5:如果writtenId不等于-1,表示该对象已被序列化,直接序列化ID,直接返回true,然后结束writeClassAndObject该方法,表示该对象实例完成。

代码@6:为object构建一个ID,这个ID数据是在一次嵌套调用writeClassAndObjec

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值