redis对象编码源码阅读——有序集合编码和转码

本文深入探讨Redis有序集合的两种编码方式:压缩列表和跳表,详细阐述它们之间的转换过程,包括压缩列表转跳表的步骤,以及转换原因在于节省空间。同时提到跳表在避免全表扫描上的优势。
摘要由CSDN通过智能技术生成

redis对象编码源码阅读——有序集合编码和转码

1. 有序集合对象的编码类型

类型 编码 对象
REDIS_ZSET REDIS_ENCODING_ZIPLIST 使用压缩列表对象实现的有序集合对象
REDIS_ZSET REDIS_ENCODING_SKIPLIST 使用跳跃表和字典实现的有序集合对象

2. 两种编码的转换

void zsetConvert(robj *zobj, int encoding) {
   
    zset *zs;
    zskiplistNode *node, *next;
    robj *ele;
    double score;

    if (zobj->encoding == encoding) return;

2.1 压缩列表转跳表

    if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
   
        unsigned char *zl = zobj->ptr;
        unsigned char *eptr, *sptr;
        unsigned char *vstr;
        unsigned int vlen;
        long long vlong;

        if (encoding != REDIS_ENCODING_SKIPLIST)
            redisPanic("Unknown target encoding");
  1. 重新申请空间
        zs = zmalloc(sizeof(*zs));
        zs->dict = dictCreate(&zsetDictType,NULL);
        zs->zsl = zslCreate();
  1. 得到 eptr = ziplist[0]sptr = ziplist[1] = ziplist[0]->next 指针
        eptr = ziplistIndex(zl,0);
        redisAssertWithInfo(NULL,zobj,eptr != NULL);
        sptr = ziplistNext(zl,eptr);
        redisAssertWithInfo(NULL,zobj,sptr != NULL);
  • ziplistIndex: 通过下标index,得到ziplist[index]
/* Returns an offset to use for iterating with ziplistNext. When the given
 * index is negative, the list is traversed back to front. When the list
 * doesn't contain an element at the provided index, NULL is returned. */
unsigned char *ziplistIndex(unsigned char *zl, int index) {
   
    unsigned char *p;
    unsigned int prevlensize, prevlen = 0;
    // 当 index < 0 的时候,反向遍历找到对应位置
    // 比如 index = -2, 就是倒数第二个节点
    // 注意:倒数第一个节点是 ZIP_END
    if (index < 0) {
   
        index = (-index)-1;
        // 得到压缩列表的尾节点
        p = ZIPLIST_ENTRY_TAIL(zl);
        if (p[0] != ZIP_END) {
   
            // 得到前一个节点的长度
            ZIP_DECODE_PREVLEN(p, prevlensize, prevlen);
            while (prevlen > 0 && index--) {
   
                p -= prevlen;
                ZIP_DECODE_PREVLEN(p, prevlensize, prevlen);
            }
        }
    // 正向遍历
    } else 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值