Redis的寻址过程[理解]

Redis的寻址过程


经常用Redis的道友是否有想过Redis如何寻址的呢?如果网上搜一下,发现很多答案不外乎如下例子,但对于答案中的每一条如何理解呢,有时甚至云里雾里,在这里记录一下我的理解

  1. Redis拿到一个 key 后,先判断当前库的 0 号和1号哈希表是否为空,如果为 true 直接返回 NULL。源码如下:
if (d->ht[0].used + d->ht[1].used == 0) return NULL; /* dict is empty */

这里的疑问是所谓的“0号”、“1号”哈希表是啥子东西?Redis在底层采用的是哈希表+链表实现的,其数据为dict 类型,使用的两个指向哈希表的指针,其中 0 号哈希表(ht[0])主要用于存储数据库的所有键值,而 1 号哈希表主要用于程序对 0 号哈希表进行 rehash 时使用,rehash 一般是在添加新值时会触发。(为什么需要rehash?这就需要了解哈希碰撞了~)如源码中dict.h文件的申明:

typedef struct dict {
    dictType *type;
    void *privdata;
    dictht ht[2];/*这里申明了哈希表的数组,数量为2*/
    long rehashidx; /* rehashing not in progress if rehashidx == -1 */
    unsigned long iterators; /* number of iterators currently running */
} dict;

  1. 判断该 0 号哈希表是否需要 rehash,因为如果在进行 rehash,那么两个表中都有可能存储该 key。如果正在进行 rehash,将调用一次_dictRehashStep 方法,_dictRehashStep 用于对数据库字典、以及哈希键的字典进行被动 rehash。
if (dictIsRehashing(d)) _dictRehashStep(d);/*判断是否需要进行重哈希*/

为什么取值需要判断是否在重哈希呢?在_dictRehashStep 方法中有这么一段解释,第一个原因应该是防止在重哈希的时候,有迭代器去修改了元素,第二个原因也是判断是否需要重哈希,当表空间不够,表经常发生哈希碰撞,此时就要考虑重哈希了。

/* This function performs just a step of rehashing, and only if there are
 * no safe iterators bound to our hash table. When we have iterators in the
 * middle of a rehashing we can't mess with the two hash tables otherwise
 * some element can be missed or duplicated.
 *
 * This function is called by common lookup or update operations in the
 * dictionary so that the hash table automatically migrates from H1 to H2
 * while it is actively used. */
static void _dictRehashStep(dict *d) {
    if (d->iterators == 0) dictRehash(d,1);
}

  1. 计算哈希表,根据当前字典与 key 进行哈希值的计算。因为保存key时,都是先算哈希值,通过哈希值进行保存。
h = dictHashKey(d, key);

  1. 根据哈希值与当前字典计算哈希表的索引值。
for (table = 0; table <= 1; table++) {//遍历两张哈希表
        idx = h & d->ht[table].sizemask;/表的大小和哈希值进行与操作
        he = d->ht[table].table[idx];
        while(he) {
            if (key==he->key || dictCompareKeys(d, key, he->key))
                return he;
            he = he->next;
        }
        if (!dictIsRehashing(d)) return NULL;
    }

  1. 根据索引值在哈希表中取出链表,遍历该链表找到 key 的位置。一般情况,该链表长度为 1。当 ht[0] 查找完了之后,再进行了次 rehash 判断,如果未在 rehashing,则直接结束,否则对 ht[1]重复 345 步骤。
    为什么需要再次判断呢?因为如果没有重哈希,那么第二张表是空的也就没有判断的必要了。
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

legendaryhaha

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值