Redis源碼剖析之字典(dict)

Dict在redis中是最爲核心的一個數據結構,由於它承載了redis裏的全部數據,你能夠簡單粗暴的認爲redis就是一個大的dict,裏面存儲的全部的key-value。html

redis中dict的本質其實就是一個hashtable,因此它也須要考慮全部hashtable全部的問題,如何組織K-V、如何處理hash衝突、擴容策略及擴容方式……。實際上Redis中hashtable的實現方式就是普通的hashtable,但Redis創新的引入了漸進式hash以減少hashtable擴容是對性能帶來的影響,接下來咱們就來看看redis中hashtable的具體實現。java

Redis中Dict的實現

dict的定義在dict.h中,其各個字段及其含義以下:git

typedef struct dict {
    dictType *type;  // dictType結構的指針,封裝了不少數據操做的函數指針,使得dict能處理任意數據類型(相似面嚮對象語言的interface,能夠重載其方法)
    void *privdata;  // 一個私有數據指針(privdata),由調用者在建立dict的時候傳進來。
    dictht ht[2];  // 兩個hashtable,ht[0]爲主,ht[1]在漸進式hash的過程當中纔會用到。  
    long rehashidx; /* 增量hash過程過程當中記錄rehash執行到第幾個bucket了,當rehashidx == -1表示沒有在作rehash */
    unsigned long iterators; /* 正在運行的迭代器數量 */
} dict;

重點介紹下dictType *type字段(我的感受命名爲type不太合適),其做用就是爲了讓dict支持各類數據類型,由於不一樣的數據類型須要對應不一樣的操做函數,好比計算hashcode 字符串和整數的計算方式就不同, 因此dictType經過函數指針的方式,將不一樣數據類型的操做都封裝起來。從面相對象的角度來看,能夠把dictType當成dict中各類數據類型相關操做的interface,各個數據類型只須要實現其對應的數據操做就行。 dictType中封裝瞭如下幾個函數指針。github

typedef struct dictType {
    uint64_t (*hashFunction)(const void *key);  // 對key生成hash值 
    void *(*keyDup)(void *privdata, const void *key); // 對key進行拷貝 
    void *(*valDup)(void *privdata, const void *obj);  // 對val進行拷貝
    int (*keyCompare)(void *privdata, const void *key1, const void *key2); // 兩個key的對比函數
    void (*keyDestructor)(void *privdata, void *key); // key的銷燬
    void (*valDestructor)(void *privdata, void *obj); // val的銷燬 
} dictType;

dict中還有另一個重要的字段dictht ht[2],dictht其實就是hashtable,但這裏爲何是ht[2]? 這就不得不提到redis dict的漸進式hash,dict的hashtable的擴容不是一次性完成的,它是先創建一個大的新的hashtable存放在ht[1]中,而後逐漸把ht[0]的數據遷移到ht[1]中,rehashidx就是ht[0]中數據遷移的進度,漸進式hash的過程會在後文中詳解。redis

這裏咱們來看下dictht的定義:編程

typedef struct dictht {
    dictEntry **table;  // hashtable中的連續空間 
    unsigned long size; // table的大小 
    unsigned long sizemask;  // hashcode的掩碼  
    unsigned long used; // 已存儲的數據個數
} dictht;

其中dictEntry就是對dict中每對key-value的封裝,除了具體的key-value,其還包含一些其餘信息,具體以下:api

typedef struct dictEntry {
    void *key;
    union {   // dictEntry在不一樣用途時存儲不一樣的數據 
        void *val;
        uint64_t u64;
        int64_t s64;
        double d;
    } v;
    struct dictEntry *next; // hash衝突時開鏈,單鏈表的next指針 
} dictEntry;

dict中的hashtable在出現hash衝突時採用的是開鏈方式,若是有多個entry落在同一個bucket中,那麼他們就會串成一個單鏈表存儲。數據結構

若是咱們將dict在內存中的存儲繪製出來,會是下圖這個樣子。
在這裏插入圖片描述dom

擴容

在看dict幾個核心API實現以前,咱們先來看下dict的擴容,也就是redis的漸進式hash。 何爲漸進式hash?redis爲何採用漸進式hash?漸進式hash又是如何實現的?函數

要回答這些問題,咱們先來考慮下hashtable擴容的過程。若是熟悉java的同窗可能知道,java中hashmap的擴容是在數據元素達到某個閾值後,新建一個更大的空間,一次性把舊數據搬過去,搬完以後再繼續後續的操做。若是數據量過大的話,HashMap擴容是很是耗時的,全部有些編程規範推薦new HashMap時最好指定其容量,防止出現自動擴容。

可是redis在新建dict的時候,無法知道數據量大小,若是直接採用java hashmap的擴容方式,由於redis是單線程的,勢必在擴容過程當中啥都幹不了,阻塞掉後面的請求,最終影響到整個redis的性能。如何解決? 其實也很簡單,就是化整爲零,將一次大的擴容操做拆分紅屢次小的步驟,一步步來減小擴容對其餘操做的影響,其具體實現以下:

上文中咱們已經看到了在dict的定義中有個dictht ht[2],dict在擴容過程當中會有兩個hashtable分別存儲在ht[0]和ht[1]中,其中ht[0]是舊的hashtable,ht[1]是新的更大的hashtable。

/* 檢查是否dict須要擴容 */
static int _dictExpandIfNeeded(dict *d)
{
    /* 已經在漸進式hash的流程中了,直接返回 */
    if (dictIsRehashing(d)) return DICT_OK;

    /* If the hash table is empty expand it to the initial size. */
    if (d->ht[0].size == 0) return dictExpand(d, DICT_HT_INITIAL_SIZE);

    /* 當配置了可擴容時,容量負載達到100%就擴容。配置不可擴容時,負載達到5也會強制擴容*/
    if (d->ht[0].used >= d->ht[0].size &&
        (dict_can_resize ||
         d->ht[0].used/d->ht[0].size > dict_force_resize_ratio))
    {
        return dictExpand(d, d->ht[0].used*2); // 擴容一倍容量
    }
    return DICT_OK;
}

Redis在每次查找某個key的索引下標時都會檢查是否須要對ht[0]作擴容,若是配置的是能夠擴容 那麼當hashtable使用率超過100%(uesed/size)就觸發擴容,不然使用率操做500%時強制擴容。執行擴容的代碼以下:

/* dict的建立和擴容 */ 
int dictExpand(dict *d, unsigned long size)
{
    /* 若是size比hashtable中的元素個數還小,那size就是無效的,直接返回error */
    if (dictIsRehashing(d) || d->ht[0].used > size)
        return DICT_ERR;

    dictht n; /* 新的hashtable */
    // 擴容時新table容量是大於當前size的最小2的冪次方,但有上限 
    unsigned long realsize = _dictNextPower(size);

    // 若是新容量和舊容量一致,沒有必要繼續執行了,返回err
    if (realsize == d->ht[0].size) return DICT_ERR;

    /* 新建一個容量更大的hashtable */
    n.size = realsize;
    n.sizemask = realsize-1;
    n.table = zcalloc(realsize*sizeof(dictEntry*));
    n.used = 0;

    // 若是是dict初始化的狀況,直接把新建的hashtable賦值給ht[0]就行 
    if (d->ht[0].table == NULL) {
        d->ht[0] = n;
        return DICT_OK;
    }

    // 非初始化的狀況,將新表賦值給ht[1], 而後標記rehashidx 0
    d->ht[1] = n;
    d->rehashidx = 0; // rehashidx表示當前rehash到ht[0]的下標位置
    return DICT_OK;
}

這裏dictExpand只是建立了新的空間,將rehashidx標記爲0(rehashidx==-1表示不在rehash的過程當中),並未對ht[0]中的數據遷移到ht[1]中。數據遷移的邏輯都在_dictRehashStep()中。 _dictRehashStep()是隻遷移一個bucket,它在dict的查找、插入、刪除的過程當中都會被調到,每次調用至少遷移一個bucket。 而dictRehash()是_dictRehashStep()的具體實現,代碼以下:

/* redis漸進式hash,採用分批的方式,逐漸將ht[0]依下標轉移到ht[2],避免了hashtable擴容時大量
 * 數據遷移致使的性能問題
 * 參數n是指此次rehash只作n個bucket */
int dictRehash(dict *d, int n) {
    int empty_visits = n*10; /* 最大空bucket數量,若是遇到empty_visits個空bucket,直接結束當前rehash的過程 */
    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; // 若是遇到了empty_visits個空的bucket,直接結束 
        }
        // 遍歷當前bucket中的鏈表,直接將其移動到新的hashtable中  
        de = d->ht[0].table[d->rehashidx];
        /* 把全部的key從舊的hash桶移到新的hash桶中 */
        while(de) {
            uint64_t h;

            nextde = de->next;
            /* 獲取到key在新hashtable中的下標 */
            h = dictHashKey(d, de->key) & d->ht[1].sizemask;
            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++;
    }

    /* 檢測是否已對全表作完了rehash */
    if (d->ht[0].used == 0) {
        zfree(d->ht[0].table);  // 釋放舊ht所佔用的內存空間  
        d->ht[0] = d->ht[1];  // ht[0]始終是在用ht,ht[1]始終是新ht,ht0全遷移到ht1後會交換下  
        _dictReset(&d->ht[1]);
        d->rehashidx = -1;   
        return 0;  // 若是全表hash完,返回0
    }

    /* 還須要繼續作hash返回1 */
    return 1;
}

能夠看出,rehash就是分批次把ht[0]中的數據搬到ht[1]中,這樣將原有的一個大操做拆分爲不少個小操做逐步進行,避免了redis發生dict擴容是瞬時不可用的狀況,缺點是在redis擴容過程當中會佔用倆份存儲空間,並且佔用時間會比較長。

核心API

插入

/* 向dict中添加元素 */
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;
}

/* 添加和查找的底層實現:  
 * 這個函數只會返回key對應的entry,並不會設置key對應的value,而是把設值權交給調用者。 
 * 
 * 這個函數也做爲一個API直接暴露給用戶調用,主要是爲了在dict中存儲非指針類的數據,好比
 * entry = dictAddRaw(dict,mykey,NULL);
 * if (entry != NULL) dictSetSignedIntegerVal(entry,1000);
 *
 * 返回值:
 * 若是key已經存在於dict中了,直接返回null,並把已經存在的entry指針放到&existing裏。不然
 * 爲key新建一個entry並返回其指針。 
*/
dictEntry *dictAddRaw(dict *d, void *key, dictEntry **existing)
{
    long index;
    dictEntry *entry;
    dictht *ht;

    if (dictIsRehashing(d)) _dictRehashStep(d);

    /* 獲取到新元素的下標,若是返回-1標識該元素已經存在於dict中了,直接返回null */
    if ((index = _dictKeyIndex(d, key, dictHashKey(d,key), existing)) == -1)
        return NULL;

    /* 不然就給新元素分配內存,並將其插入到鏈表的頭部(通常新插入的數據被訪問的頻次會更高)*/
    ht = dictIsRehashing(d) ? &d->ht[1] : &d->ht[0];
    entry = zmalloc(sizeof(*entry));
    entry->next = ht->table[index];
    ht->table[index] = entry;
    ht->used++;

    /* 若是是新建的entry,須要把key填進去 */
    dictSetKey(d, entry, key);
    return entry;
}

插入過程也比較簡單,就是先定位bucket的下標,而後插入到單鏈表的頭節點,注意這裏也須要考慮到rehash的狀況,若是是在rehash過程當中,新數據必定是插入到ht[1]中的。

查找

dictEntry *dictFind(dict *d, const void *key)
{
    dictEntry *he;
    uint64_t h, idx, table;

    if (dictSize(d) == 0) return NULL; /* dict爲空 */
    if (dictIsRehashing(d)) _dictRehashStep(d);
    h = dictHashKey(d, key);
    // 查找的過程當中,可能正在rehash中,因此新老兩個hashtable都須要查 
    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;
        }
        // 若是ht[0]中沒找到,且再也不rehas中,就不須要繼續找了ht[1]了。 
        if (!dictIsRehashing(d)) return NULL;
    }
    return NULL;
}

查找的過程比較簡單,就是用hashcode作定位,而後遍歷單鏈表。但這裏須要考慮到若是是在rehash過程當中,可能須要查找ht[2]中的兩個hashtable。

刪除

/* 查找並刪除一個元素,是dictDelete()和dictUnlink()的輔助函數。*/
static dictEntry *dictGenericDelete(dict *d, const void *key, int nofree) {
    uint64_t h, idx;
    dictEntry *he, *prevHe;
    int table;

    if (d->ht[0].used == 0 && d->ht[1].used == 0) return NULL;

    if (dictIsRehashing(d)) _dictRehashStep(d);
    h = dictHashKey(d, key);

    // 這裏也是須要考慮到rehash的狀況,ht[0]和ht[1]中的數據都要刪除掉 
    for (table = 0; table <= 1; table++) {
        idx = h & d->ht[table].sizemask;
        he = d->ht[table].table[idx];
        prevHe = NULL;
        while(he) {
            if (key==he->key || dictCompareKeys(d, key, he->key)) {
                /* 從列表中unlink掉元素 */
                if (prevHe)
                    prevHe->next = he->next;
                else
                    d->ht[table].table[idx] = he->next;
                // 若是nofree是0,須要釋放k和v對應的內存空間 
                if (!nofree) {
                    dictFreeKey(d, he);
                    dictFreeVal(d, he);
                    zfree(he);
                }
                d->ht[table].used--;
                return he;
            }
            prevHe = he;
            he = he->next;
        }
        if (!dictIsRehashing(d)) break;
    }
    return NULL; /* 沒找到key對應的數據 */
}

其它API

其餘的API實現都比較簡單,我在dict.c源碼中作了大量的註釋,有興趣能夠自行閱讀下,我這裏僅列舉並說明下其大體的功能。

dict *dictCreate(dictType *type, void *privDataPtr);  // 建立dict 
int dictExpand(dict *d, unsigned long size);  // 擴縮容
int dictAdd(dict *d, void *key, void *val);  // 添加k-v
dictEntry *dictAddRaw(dict *d, void *key, dictEntry **existing); // 添加的key對應的dictEntry 
dictEntry *dictAddOrFind(dict *d, void *key); // 添加或者查找 
int dictReplace(dict *d, void *key, void *val); // 替換key對應的value,若是沒有就添加新的k-v
int dictDelete(dict *d, const void *key);  // 刪除某個key對應的數據 
dictEntry *dictUnlink(dict *ht, const void *key); // 卸載某個key對應的entry 
void dictFreeUnlinkedEntry(dict *d, dictEntry *he); // 卸載並清除key對應的entry
void dictRelease(dict *d);  // 釋放整個dict 
dictEntry * dictFind(dict *d, const void *key);  // 數據查找
void *dictFetchValue(dict *d, const void *key);  // 獲取key對應的value
int dictResize(dict *d);  // 重設dict的大小,主要是縮容用的
/************    迭代器相關     *********** */
dictIterator *dictGetIterator(dict *d);  
dictIterator *dictGetSafeIterator(dict *d);
dictEntry *dictNext(dictIterator *iter);
void dictReleaseIterator(dictIterator *iter);
/************    迭代器相關     *********** */
dictEntry *dictGetRandomKey(dict *d);  // 隨機返回一個entry 
dictEntry *dictGetFairRandomKey(dict *d);   // 隨機返回一個entry,但返回每一個entry的機率會更均勻 
unsigned int dictGetSomeKeys(dict *d, dictEntry **des, unsigned int count); // 獲取dict中的部分數據

其餘的API見代碼dict.cdict.h.

本文是Redis源碼剖析系列博文,同時也有與之對應的Redis中文註釋版,有想深刻學習Redis的同窗,歡迎star和關注。
Redis中文註解版倉庫:https://github.com/xindoo/Redis
Redis源碼剖析專欄:https://zxs.io/s/1h
若是以爲本文對你有用,歡迎一鍵三連
本文來自https://blog.csdn.net/xindoo

相關文章
相關標籤/搜索