redis源码分析1------dict的实现

lh-ty 2018-11-09 原文

redis源码分析1——dict的实现

1. 总体结构

redis的dict就是hash表,使用链式结构来解决key值冲突,典型的数据结构

结构体的定义如下:



typedef struct dictEntry {
    void *key;
    union {
        void *val;
        uint64_t u64;
        int64_t s64;
        double d;
    } v;
    struct dictEntry *next;
} dictEntry;

typedef struct dictType {
    uint64_t (*hashFunction)(const void *key);
    void *(*keyDup)(void *privdata, const void *key);
    void *(*valDup)(void *privdata, const void *obj);
    int (*keyCompare)(void *privdata, const void *key1, const void *key2);
    void (*keyDestructor)(void *privdata, void *key);
    void (*valDestructor)(void *privdata, void *obj);
} dictType;

/* 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 {
    dictEntry **table;
    unsigned long size;  //这个是hash桶的大小
    unsigned long sizemask;  //hash桶大小-1, **用hash**/sizemask来计算桶下标
    unsigned long used; //当前这个dict一共放了多少个kv键值对
} dictht;
//一旦used/size >=dict_force_resize_ratio(默认值是5),就会触发rehash,可以理解为一个hash桶后面平均挂载的冲突队列个数为5的时候,就会触发rehash


typedef struct dict {
    dictType *type;
    void *privdata;
    dictht ht[2];
    long rehashidx; /* rehashing not in progress if rehashidx == -1 */
    unsigned long iterators; /* number of iterators currently running */
} dict;


如下图所示:

2. API接口分析

2.1 创建

API接口函数:

**2.1.1 在dict中增加一个k-v键值对 — dictAdd(dict d, void key, void *val)**

/* Add an element to the target hash table */
int dictAdd(dict *d, void *key, void *val)
{
    dictEntry *entry = dictAddRaw(d,key,NULL);//调用了内部函数

    if (!entry) return DICT_ERR;
    dictSetVal(d, entry, val);
    return DICT_OK;
}



dictEntry *dictAddRaw(dict *d, void *key, dictEntry **existing)
{
    long index;
    dictEntry *entry;
    dictht *ht;

    if (dictIsRehashing(d)) _dictRehashStep(d); //如果正在rehash进行中,则每次操作都尝试进行一次rehash操作

    /* Get the index of the new element, or -1 if
     * the element already exists. 获取到hash桶的入口index*/
    if ((index = _dictKeyIndex(d, key, dictHashKey(d,key), existing)) == -1)
        return NULL;

    /* Allocate the memory and store the new entry.
     * Insert the element in top, with the assumption that in a database
     * system it is more likely that recently added entries are accessed
     * more frequently. 这里的实现和一般的hash链式解决冲突的实现有点小不同, 
     这里是把新插入的entry放到了链表头上,可以看上面的英文解释*/
    ht = dictIsRehashing(d) ? &d->ht[1] : &d->ht[0];
    entry = zmalloc(sizeof(*entry));
    entry->next = ht->table[index];
    ht->table[index] = entry;
    ht->used++;

    /* Set the hash entry fields.*/
    dictSetKey(d, entry, key);
    return entry;
}


/* Returns the index of a free slot that can be populated with
 * a hash entry for the given 'key'.
 * If the key already exists, -1 is returned
 * and the optional output parameter may be filled.
 *
 * Note that if we are in the process of rehashing the hash table, the
 * index is always returned in the context of the second (new) hash table. 
 
 这个原版注释写的很清楚,如果正在rehashing的时候,index返回的是new的hashtable*/
static long _dictKeyIndex(dict *d, const void *key, uint64_t hash, dictEntry **existing)
{
    unsigned long idx, table;
    dictEntry *he;
    if (existing) *existing = NULL;

    /* Expand the hash table if needed ,判断hash桶是否需要扩大,这个地方是redis比较牛逼的地方,  
    hash桶是动态扩大的,默认初始的时候只有4,然后每次乘2的方式进行扩展,如果扩展了,就需要进行rehash*/
    if (_dictExpandIfNeeded(d) == DICT_ERR)
        return -1;
    /*获取索引的时候,如果正在rehash,需要两个hashtable都进行查询*/
    for (table = 0; table <= 1; table++) {
        /*这个idx就是hash桶的下标*/
        idx = hash & d->ht[table].sizemask;
        /* Search if this slot does not already contain the given key */
        he = d->ht[table].table[idx];
        while(he) {
        /*这里是必须遍历下冲突队列,保证key没有出现过*/
            if (key==he->key || dictCompareKeys(d, key, he->key)) {
                if (existing) *existing = he;
                return -1;
            }
            he = he->next;
        }
        /*如果不在rehash的话,其实就没有必要再做rehash的操作,直接返回就好了*/
        if (!dictIsRehashing(d)) break;
    }
    return idx;
}



3. rehash过程
redis对于dict支持两种rehash的方式:按照时间,或者按照操作进行rehash。每次都hash一个key值桶。
rehash 代码如下:

static void _dictRehashStep(dict *d) {
    if (d->iterators == 0) dictRehash(d,1);
}


/* Performs N steps of incremental rehashing. Returns 1 if there are still
 * keys to move from the old to the new hash table, otherwise 0 is returned.
 *
 * Note that a rehashing step consists in moving a bucket (that may have more
 * than one key as we use chaining) from the old to the new hash table, however
 * since part of the hash table may be composed of empty spaces, it is not
 * guaranteed that this function will rehash even a single bucket, since it
 * will visit at max N*10 empty buckets in total, otherwise the amount of
 * work it does would be unbound and the function may block for a long time. */
int dictRehash(dict *d, int n) {
    int empty_visits = n*10; /* Max number of empty buckets to visit. */
    if (!dictIsRehashing(d)) return 0;

    while(n-- && d->ht[0].used != 0) {
        dictEntry *de, *nextde;

        /* Note that rehashidx can't overflow as we are sure there are more
         * elements because ht[0].used != 0 */
        assert(d->ht[0].size > (unsigned long)d->rehashidx);
        while(d->ht[0].table[d->rehashidx] == NULL) {
            d->rehashidx++;
            if (--empty_visits == 0) return 1; //redis为了保证性能,扫描空桶,最多也是有一定的限制
        }
        de = d->ht[0].table[d->rehashidx];
        /* Move all the keys in this bucket from the old to the new hash HT ,这个循环就是开始把这个rehashidx下标的hashtable迁移到新的下标下面,注意,这里需要重新计算key值,重新插入*/
        while(de) {
            uint64_t h;

            nextde = de->next;
            /* Get the index in the new hash table */
            h = dictHashKey(d, de->key) & d->ht[1].sizemask;//重新计算key值,重新插入
            de->next = d->ht[1].table[h];
            d->ht[1].table[h] = de;
            d->ht[0].used--;
            d->ht[1].used++;
            de = nextde;
        }
        d->ht[0].table[d->rehashidx] = NULL;
        d->rehashidx++;
    }

    /* Check if we already rehashed the whole table...,一次操作完了,可能这个hashtable已经迁移完毕,返回0,否则返回1 */
    if (d->ht[0].used == 0) {
        zfree(d->ht[0].table);
        d->ht[0] = d->ht[1]; //现在的0变成1
        _dictReset(&d->ht[1]);  //现在的1被reset掉
        d->rehashidx = -1;
        return 0;
    }

    /* More to rehash... */
    return 1;
}


发表于 2018-11-09 15:50 Lh_blog 阅读() 评论() 编辑 收藏

 

版权声明:本文为lh-ty原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/lh-ty/p/9935542.html

redis源码分析1------dict的实现的更多相关文章

随机推荐

  1. leetcode刷题笔记326 3的幂

    题目描述: 给出一个整数,写一个函数来确定这个数是不是3的一个幂。 后续挑战:你能不使用循环或者递归完成本题吗 […]...

  2. 教老婆学Linux运维(二)Linux常用命令指南【上】

    目录 教老婆学Linux(二)Linux常用命令指南【上】 一、概述 二、常用命令 教老婆学Linux(二)L […]...

  3. freeRTOS内核学习笔记(1)-编程标准

    在开始具体的学习之前,你应该先了解freeRTOS的编程标准.这能够方便你在接下来的阅读中快速的了解一些内容 […]...

  4. 二进制计算方法

    二进制的算术运算: 二进制加法 1 根据“逢二进一”规则,二进制加法法则: 2 0+0=0 3 0+1=1+0 […]...

  5. 超值干货 | 建议收藏:精美详尽的 HTTPS 原理图注意查收!

    作为一个有追求的程序员,了解行业发展趋势和扩充自己的计算机知识储备都是很有必要的,特别是一些计算机基础方面的内 […]...

  6. 第1篇-关于JVM运行时,开篇说的简单些

    第1篇-关于JVM运行时,开篇说的简单些 开讲Java运行时,这一篇讲一些简单的内容。我们写的主类中的main […]...

  7. mongols的反向代理和负载均衡功能

    mongols是C++ 服务器基础设施库,它最近更新提供了反向代理和负载均衡功能。 以下为用mongols代理 […]...

  8. 25岁的程序员,如何做才能在35岁时不焦虑

    ​无论是在知乎、公众号或各种技术论坛,程序员的35岁门槛问题总会成为大家热议的话题。 最近在和团队的小伙伴谈话 […]...

展开目录

目录导航