redis数据结构之Dict

我们知道Redis是一个键值型(Key-Value Pair)的数据库,我们可以根据键实现快速的增删改查。而键与值的映射关系正是通过Dict来实现的。

Dict由三部分组成,分别是:哈希表(DictHashTable)、哈希节点(DictEntry)、字典(Dict)。哈希表和哈希节点对应的结构体如下:

/* This is our hash table structure. Every dictionary has two of this as we
 * implement incremental rehashing, for the old to the new table. */
typedef struct dictht {
    // entry数组,数组中保存的是指向entry的指针
    dictEntry **table;
    // 哈希表大小
    unsigned long size;
    // 哈希表大小的掩码,总等于size - 1
    unsigned long sizemask;
    // entry个数
    unsigned long used;
} dictht;
typedef struct dictEntry {
    void *key;  // 键
    union {
        void *val;
        uint64_t u64;
        int64_t s64;
        double d;
    } v;  // 值
    // 指向下一个Entry的指针
    struct dictEntry *next;
} dictEntry;

当我们向Dict添加键值对时,Redis首先根据key计算出hash值(h),然后利用h & sizemask来计算元素应该存储到数组中的哪个索引位置。我们存储k1=v1,假设k1的哈希值h =1,则1&3 =1,因此k1=v1要存储到数组角标1位置。

在这里插入图片描述
字典的结构体如下:

typedef struct dict {
    // dict类型,内置不同的hash函数
    dictType *type;
    // 私有数据,在做特殊hash运算时用
    void *privdata;
    // 一个Dict包括两个hash表,其中一个是当前数据,另一个一般是空,rehash的时候才使用
    dictht ht[2];
    // rehash的进度,-1表示未进行
    long rehashidx; /* rehashing not in progress if rehashidx == -1 */
    // rehash是否暂停,1则暂停,0则继续
    unsigned long iterators; /* number of iterators currently running */
} dict;

在这里插入图片描述
如果有兴趣了解更多相关内容,欢迎来我的个人网站看看:瞳孔的个人网站

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值