一、quicklist简介

Redis列表是简单的字符串列表,按照插入顺序排序。你可以添加一个元素到列表的头部(左边)或者尾部(右边)。

一个列表最多可以包含 232 - 1 个元素 (4294967295, 每个列表超过40亿个元素)。

其底层实现所依赖的内部数据结构就是quicklist,主要特点有:

1. list是一个双向链表。

2. 在list的两端追加和删除数据极为方便,时间复杂度为O(1)。

3. list也支持在任意中间位置的存取操作,时间复杂度为O(N)。

在看源码之前(版本3.2.2),我们先看一下quicklist中的几个主要数据结构:

一个quicklist由多个quicklistNode组成,每个quicklistNode指向一个ziplist,一个ziplist包含多个entry元素,每个entry元素就是一个list的元素,示意图如下:

                        图1:quicklist

 二、quicklist数据结构源码

下面分别看下quicklist、quicklistNode的源码(代码文件是Quicklist.h,ziplist后面文章再分析):

quicklist:

/*
quicklist结构占用32个字节(64位系统),其中字段:
head:指向第一个quicklistNode。
tail:指向最后一个quicklistNode。
count:在所有ziplist中entry的个数总和。
len:quicklistNode的个数。
fill:ziplist大小限定,由server.list_max_ziplist_size给定。
compress:节点压缩深度设置,由server.list-compress-depth给定,0表示关闭压缩。
*/
typedef struct quicklist {
quicklistNode *head;
quicklistNode *tail;
unsigned long count; /* total count of all entries in all ziplists */
unsigned int len; /* number of quicklistNodes */
int fill : ; /* fill factor for individual nodes */
unsigned int compress : ; /* depth of end nodes not to compress;0=off */
} quicklist;

quicklistNode:

/*
prev: 指向前一个quicklistNode。
next: 指向下一个quicklistNode。
zl: 指向当前节点的ziplist。
sz:ziplist占用空间的字节数。
count: ziplist中元素个数。
encoding:编码类型,RAW==1 or LZF==2。
container:容器类型,NONE==1 or ZIPLIST==2
recompress:bool类型,true表示该节点数据临时被解压了。
attempted_compress: bool类型,用于测试阶段。
extra: 填充字典,将来可能会用到。
*/
typedef struct quicklistNode {
struct quicklistNode *prev;
struct quicklistNode *next;
unsigned char *zl;
unsigned int sz; /* ziplist size in bytes */
unsigned int count : ; /* count of items in ziplist */
unsigned int encoding : ; /* RAW==1 or LZF==2 */
unsigned int container : ; /* NONE==1 or ZIPLIST==2 */
unsigned int recompress : ; /* was this node previous compressed? */
unsigned int attempted_compress : ; /* node can't compress; too small */
unsigned int extra : ; /* more bits to steal for future usage */
} quicklistNode;

三、quicklist的增删改查

1. 创建quicklist

在执行push命令时(例如lpush),发现无此key时,会创建并初始化quicklist,如下:

void pushGenericCommand(client *c, int where) {
int j, waiting = , pushed = ;
robj *lobj = lookupKeyWrite(c->db,c->argv[]); if (lobj && lobj->type != OBJ_LIST) {
addReply(c,shared.wrongtypeerr);
return;
} for (j = ; j < c->argc; j++) {
c->argv[j] = tryObjectEncoding(c->argv[j]);
if (!lobj) { // key不存在,则首先创建key对象并加入db中
lobj = createQuicklistObject(); // 初始化quicklist对象
quicklistSetOptions(lobj->ptr, server.list_max_ziplist_size,
server.list_compress_depth); // 使用redis server的配置项做初始化
dbAdd(c->db,c->argv[],lobj); // 把quicklist添加到redis db中
}
// 把新元素加入list中
listTypePush(lobj,c->argv[j],where);
pushed++;
}
addReplyLongLong(c, waiting + (lobj ? listTypeLength(lobj) : ));
if (pushed) {
char *event = (where == LIST_HEAD) ? "lpush" : "rpush"; signalModifiedKey(c->db,c->argv[]);
notifyKeyspaceEvent(NOTIFY_LIST,event,c->argv[],c->db->id);
}
server.dirty += pushed;
}

再看下createQuicklistObject:

/* Create a new quicklist.
* Free with quicklistRelease(). */
quicklist *quicklistCreate(void) {
struct quicklist *quicklist; quicklist = zmalloc(sizeof(*quicklist));
quicklist->head = quicklist->tail = NULL;
quicklist->len = ;
quicklist->count = ;
quicklist->compress = ;
quicklist->fill = -;
return quicklist;
}

2. 添加元素

继续看上面源码中的listTypePush方法:

void listTypePush(robj *subject, robj *value, int where) {
if (subject->encoding == OBJ_ENCODING_QUICKLIST) {
int pos = (where == LIST_HEAD) ? QUICKLIST_HEAD : QUICKLIST_TAIL;
value = getDecodedObject(value);
size_t len = sdslen(value->ptr);// 计算新元素长度
quicklistPush(subject->ptr, value->ptr, len, pos); // 加入到quicklist
decrRefCount(value);
} else {
serverPanic("Unknown list encoding");
}
}

继续看quicklistPush:

/* Wrapper to allow argument-based switching between HEAD/TAIL pop */
void quicklistPush(quicklist *quicklist, void *value, const size_t sz,
int where) {
if (where == QUICKLIST_HEAD) { // 添加到list头部
quicklistPushHead(quicklist, value, sz);
} else if (where == QUICKLIST_TAIL) { // 添加到list尾部
quicklistPushTail(quicklist, value, sz);
}
} /* Add new entry to head node of quicklist.
*
* Returns 0 if used existing head.
* Returns 1 if new head created.
在quicklist的头部节点添加新元素:
如果新元素添加在head中,返回0,否则返回1.
*/
int quicklistPushHead(quicklist *quicklist, void *value, size_t sz) {
quicklistNode *orig_head = quicklist->head;
// 如果head不为空,且空间大小满足新元素的存储要求,则新元素添加到head中,否则新加一个quicklistNode
if (likely(
_quicklistNodeAllowInsert(quicklist->head, quicklist->fill, sz))) {
quicklist->head->zl =
ziplistPush(quicklist->head->zl, value, sz, ZIPLIST_HEAD);
quicklistNodeUpdateSz(quicklist->head);
} else {
// 创建新的quicklistNode
quicklistNode *node = quicklistCreateNode();
// 把新元素添加到新建的ziplist中
node->zl = ziplistPush(ziplistNew(), value, sz, ZIPLIST_HEAD);
// 更新ziplist的长度到quicklistNode的sz字段,再把新node添加到quicklist中,即添加到原head前面
quicklistNodeUpdateSz(node);
_quicklistInsertNodeBefore(quicklist, quicklist->head, node);
}
quicklist->count++;
quicklist->head->count++;
return (orig_head != quicklist->head);
}

ziplistpush会把新元素添加到ziplist中,这部分代码后面文章再分析。

3. 获取元素

获取元素方法是quicklistPop方法(quicklist.c),如下:

/* Default pop function
*
* Returns malloc'd value from quicklist */
int quicklistPop(quicklist *quicklist, int where, unsigned char **data,
unsigned int *sz, long long *slong) {
unsigned char *vstr;
unsigned int vlen;
long long vlong;
if (quicklist->count == )
return ;
// pop一个元素
int ret = quicklistPopCustom(quicklist, where, &vstr, &vlen, &vlong,
_quicklistSaver);
if (data)
*data = vstr;
if (slong)
*slong = vlong;
if (sz)
*sz = vlen;
return ret;
}

具体实现在quicklistPopCustom:

/* pop from quicklist and return result in 'data' ptr.  Value of 'data'
* is the return value of 'saver' function pointer if the data is NOT a number.
*
* If the quicklist element is a long long, then the return value is returned in
* 'sval'.
*
* Return value of 0 means no elements available.
* Return value of 1 means check 'data' and 'sval' for values.
* If 'data' is set, use 'data' and 'sz'. Otherwise, use 'sval'.
如果quicklist中无元素,返回0,否则返回1.
当返回1时,需要检查data和sval两个字段:
1. 如果是string类型,则把结果地址保存在data指针中,长度保存在sz。
2. 如果是long long类型,则把值保存在sval字段中。
*/
int quicklistPopCustom(quicklist *quicklist, int where, unsigned char **data,
unsigned int *sz, long long *sval,
void *(*saver)(unsigned char *data, unsigned int sz)) {
unsigned char *p;
unsigned char *vstr;
unsigned int vlen;
long long vlong;
int pos = (where == QUICKLIST_HEAD) ? : -; if (quicklist->count == )
return ; if (data)
*data = NULL;
if (sz)
*sz = ;
if (sval)
*sval = -; quicklistNode *node;
if (where == QUICKLIST_HEAD && quicklist->head) {
node = quicklist->head;
} else if (where == QUICKLIST_TAIL && quicklist->tail) {
node = quicklist->tail;
} else {
return ;
}
// p: 0 取ziplist的第一个元素; -1 取ziplist的最后一个元素;
p = ziplistIndex(node->zl, pos);
if (ziplistGet(p, &vstr, &vlen, &vlong)) {
if (vstr) {
if (data)
*data = saver(vstr, vlen);
if (sz)
*sz = vlen;
} else {
if (data)
*data = NULL;
if (sval)
*sval = vlong;
}
// 从quicklist中删除该元素
quicklistDelIndex(quicklist, node, &p);
return ;
}
return ;
}

再看下quicklistDelIndex:

/* Delete one entry from list given the node for the entry and a pointer
* to the entry in the node.
*
* Note: quicklistDelIndex() *requires* uncompressed nodes because you
* already had to get *p from an uncompressed node somewhere.
*
* Returns 1 if the entire node was deleted, 0 if node still exists.
* Also updates in/out param 'p' with the next offset in the ziplist.
从quicklistNode中删除一个entry:
1. 从ziplist中删除entry。
2. quicklistNode中的entry个数减1:
如果quicklistNode中entry个数为0,则从quicklist中删除当前的quicklistNode。
否则,更新quicklistNode中的sz字段。
*/
REDIS_STATIC int quicklistDelIndex(quicklist *quicklist, quicklistNode *node,
unsigned char **p) {
int gone = ; node->zl = ziplistDelete(node->zl, p);
node->count--;
if (node->count == ) {
gone = ;
__quicklistDelNode(quicklist, node);
} else {
quicklistNodeUpdateSz(node);
}
quicklist->count--;
/* If we deleted the node, the original node is no longer valid */
return gone ? : ;
}

至此,quicklist的主体结构代码,和主要的两个方法push和pop的代码就分析结束了,下一篇分析quicklist底层存储ziplist的源代码。

本篇内容参考了钱文品的《Redis深度历险:核心原理与应用实践》,特此感谢!

Redis之quicklist源码分析的更多相关文章

  1. Redis 内存管理 源码分析

    要想了解redis底层的内存管理是如何进行的,直接看源码绝对是一个很好的选择 下面是我添加了详细注释的源码,需要注意的是,为了便于源码分析,我把redis为了弥补平台差异的那部分代码删了,只需要知道有 ...

  2. Redis网络模型的源码分析

    Redis的网络模型是基于I/O多路复用程序来实现的.源码中包含四种多路复用函数库epoll.select.evport.kqueue.在程序编译时会根据系统自动选择这四种库其中之一.下面以epoll ...

  3. Redis之ziplist源码分析

    一.ziplist简介 从上一篇分析我们知道quicklist的底层存储使用了ziplist(压缩列表),由于压缩列表本身也有不少内容,所以重新开了一篇,在正式源码之前,还是先看下ziplist的特点 ...

  4. Redis 数据结构-字符串源码分析

    相关文章 Redis 初探-安装与使用 Redis常用指令 本文将从以下几个部分进行介绍 1.前言 2.常用命令 3.字符串结构 4.字符串实现 5.命令是如果操作字符串的 前言 平时在使用 Redi ...

  5. Redis网络库源码分析(1)之介绍篇

    一.前言 Redis网络库是一个单线程EPOLL模型的网络库,和Memcached使用的libevent相比,它没有那么庞大,代码一共2000多行,因此比较容易分析.其实网上已经有非常多有关这个网络库 ...

  6. 第10课:[实战] Redis 网络通信模块源码分析(3)

    redis-server 接收到客户端的第一条命令 redis-cli 给 redis-server 发送的第一条数据是 *1\r\n\$7\r\nCOMMAND\r\n .我们来看下对于这条数据如何 ...

  7. 第09课:【实战】Redis网络通信模块源码分析(2)

    侦听 fd 与客户端 fd 是如何挂载到 EPFD 上去的 同样的方式,要把一个 fd 挂载到 EPFD 上去,需要调用系统 API epoll_ctl ,搜索一下这个函数名.在文件 ae_epoll ...

  8. 第08课:【实战】Redis网络通信模块源码分析(1)

    我们这里先研究redis-server端的网络通信模块.除去Redis本身的业务功能以外,Redis的网络通信模块实现思路和细节非常有代表性.由于网络通信模块的设计也是Linux C++后台开发一个很 ...

  9. Redis网络库源码分析(3)之ae.c

    一.aeCreateEventLoop & aeCreateFileEvent 上一篇文章中,我们已经将服务器启动,只是其中有些细节我们跳过了,比如aeCreateEventLoop函数到底做 ...

随机推荐

  1. 后端程序员不得不会的 Nginx 转发匹配规则

    整理了一些Java方面的架构.面试资料(微服务.集群.分布式.中间件等),有需要的小伙伴可以关注公众号[程序员内点事],无套路自行领取 一口气说出 9种 分布式ID生成方式,面试官有点懵了 面试总被问 ...

  2. Js的new运算符

    new运算符 在JavaScript中,new是一个语法糖,可以简化代码的编写,可以批量创建对象实例. 语法糖Syntactic sugar,指计算机语言中添加的某种语法,这种语法对语言的功能并没有影 ...

  3. bzoj4693

    题意 bzoj 做法 结论1:对于\((X_1,X_2,...,X_k)\),其为红的充要条件为:令\(Y_i=X_i-1\),\(\prod\limits_{k=1}^K {\sum\limits_ ...

  4. 谷歌出品EfficientNet:比现有卷积网络小84倍,比GPipe快6.1倍

    [导读]谷歌AI研究部门华人科学家再发论文<EfficientNet:重新思考CNN模型缩放>,模型缩放的传统做法是任意增加CNN的深度和宽度,或使用更大的输入图像分辨率进行训练,而使用E ...

  5. 一、【Docker笔记】进入Docker世界

    ​ 我们平时判断一个电脑的性能主要看什么?磁盘读写?CPU的主频高低?还是内存的大小?可是作为个人使用者来说,这些参数高一些足够我们去使用了,可是对于一个大型系统甚至是超大型系统,当前的硬件是远远达不 ...

  6. RabbitMQ 交换机类型

    1,扇形交换机 fanout 2, 直连交换机 direct 3, 通配符交换机 topic

  7. 线程安全,syncronized 用法

    1,为什么有线程安全问题? 当多个线程同时共享同一个全局变量或静态变量,做写的操作时,可能会发生数据冲突问题,也就是线程安全问题.但是做读操作是不会发生数据冲突问题. public class Tra ...

  8. MySQL count知多少

    统计一个表的数据量是经常遇到的需求,但是不同的表设计及不同的写法,统计性能差别会有较大的差异,下面就简单通过实验进行测试(大家测试的时候注意缓存的情况,否则影响测试结果). 1. 准备工作 为了后续测 ...

  9. Spring中应用的那些设计模式

    设计模式作为工作学习中的枕边书,却时常处于勤说不用的尴尬境地,也不是我们时常忘记,只是一直没有记忆. 今天,我们就设计模式的内在价值做一番探讨,并以spring为例进行讲解,只有领略了其设计的思想理念 ...

  10. flask中温柔显示404等错误

    写下下面两个视图函数,然后在模板中写下错误时展现的内容,当然模板名,函数名是可以改的哟@app.errorhandler(404)def page_not_found(error): return r ...