redis資料結構儲存Dict設計細節(redis的設計與實現筆記)

來源:互聯網
上載者:User

標籤:興趣   並且   個數   images   tab   構造   eve   signed   bucket   

說到redis的Dict(字典),雖說演算法上跟市面上一般的Dict實現沒有什麼區別,但是redis的Dict有2個特殊的地方那就是它的rehash(重新散列)和它的字典節點單向鏈表。

以下是dict用到的結構:

typedef struct dictEntry {//字典的節點      void *key;      union {//使用的聯合體          void *val;          uint64_t u64;//這兩個參數很有用          int64_t s64;      } v;      struct dictEntry *next;//下一個節點指標  } dictEntry;    typedef struct dictType {      unsigned int (*hashFunction)(const void *key); //hash函數指標      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 { //字典hash table      dictEntry **table;//可以看做字典數組,俗稱桶bucket      unsigned long size; //指標數組的大小,即桶的層數      unsigned long sizemask;      unsigned long used; //字典中當前的節點數目  } dictht;    typedef struct dict {      dictType *type;      void *privdata; //私人資料      dictht ht[2];   //兩個hash table      int rehashidx; /* rehashing not in progress if rehashidx == -1 */ //rehash 索引      int iterators; /* number of iterators currently running */ //當前該字典迭代器個數  } dict;   

由於樓主演算法能力有限:所以對雜湊演算法沒有太深的瞭解,所以在這裡演算法就不詳寫了,大家有興趣可以百度。

當運用雜湊演算法計算出 k0的索引 ,redis就會插入到指定的位置

當k2和k1出現計算出鍵索引相同的情況下,這時候redis的dictEntry(字典節點)有一個next屬性(單項鏈表),redis會把衝突鍵索引的元素排到後插入資料的前面,從而解決了這個問題

現在如果在插入2條元素,此時資料量已經超過dict的負載了,redis就會啟用rehash,雖然是rehash操作但是redis是採用了漸進式操作,並不是一下子記憶體不夠用了 就直接操作記憶體,然後全部轉移資料,這樣會導致操作很耗時,redis考慮到了這一點,然後

先把ht[1]另一張dict結構中擴容一個數量為ht[0].used*2的dictEntry數組,然後把2條資料通過雜湊演算法加入到這個數組中。

 

然後把上面的元素一個個非同步漸漸移動到下面的數組中,在這個過程中如果用戶端去操作元素時,如果在ht[0]中檢尋找不到建,就會去檢查ht[1]中是否有指定的鍵,從而不影響資料的使用,而且可以避免一次性操作rehash帶來的耗時問題,最後reshash完成了,就直接把ht[1]和ht[0]切換位置並且清空棄用的雜湊節點數組,從而完成所有操作。

 

 

redis資料結構儲存Dict設計細節(redis的設計與實現筆記)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.