# Redis的Key是如何尋址的
## 引言
Redis作為高性能的鍵值存儲系統,其核心機制之一就是如何快速定位存儲在內存中的鍵值對。本文將深入剖析Redis的Key尋址原理,包括哈希表實現、漸進式rehash策略、內存壓縮優化等關鍵技術。
---
## 一、Redis存儲結構概述
Redis采用字典(Dict)作為核心存儲結構,其底層通過哈希表實現:
```c
// Redis 6.x 源碼結構
typedef struct dict {
dictType *type;
void *privdata;
dictht ht[2]; // 雙哈希表結構
long rehashidx; // rehash進度標識
} dict;
typedef struct dictht {
dictEntry **table; // 哈希桶數組
unsigned long size; // 桶數量
unsigned long sizemask; // size-1(用于位運算)
unsigned long used; // 已使用桶數量
} dictht;
Redis采用MurmurHash2/SipHash等算法計算鍵的哈希值:
# 偽代碼示例
def hash_function(key):
if key_type == string:
return siphash(key)
elif key_type == integer:
return int_hash(key)
hash = hash_function(key)index = hash & sizemask
// 偽代碼示例
void incrementalRehash(dict *d):
if d->rehashidx != -1:
for i in range(0, N): // 每次處理N個桶
move_bucket(d->ht[0], d->ht[1])
d->rehashidx++
if all_buckets_moved:
free(d->ht[0])
d->ht[0] = d->ht[1]
d->rehashidx = -1
| 當前容量 | 新容量 | 擴容倍數 |
|---|---|---|
| < 1M | 當前容量*4 | 4x |
| ≥ 1M | 當前容量*2 | 2x |
Redis 6.0后采用listpack替代雙向鏈表:
// 舊結構:dictEntry->next指針(8字節)
// 新結構:entry_len|key|value|next_entry_len
typedef struct redisDb {
dict *dict; // 主鍵空間
dict *expires; // 過期字典
} redisDb;
當Value超過hash-max-ziplist-value(默認64字節)時,轉為哈希表存儲。
使用redis-benchmark測試不同場景下的操作耗時:
| 數據規模 | 普通模式 | 集群模式 |
|---|---|---|
| 10萬Key | 1.2ms | 1.5ms |
| 100萬Key | 15ms | 18ms |
:分隔的層級結構(如user:1000:profile)
redis-cli info stats | grep keyspace
Redis通過精妙的哈希表設計實現O(1)時間復雜度尋址,結合漸進式rehash和內存優化,在保證性能的同時實現了動態擴展。理解這些機制有助于開發者優化Redis使用策略,構建更高性能的存儲系統。
本文基于Redis 6.2源碼分析,不同版本實現可能略有差異 “`
注:實際使用時需要: 1. 替換流程圖鏈接為真實圖片 2. 補充具體的性能測試數據 3. 根據Redis版本差異調整細節描述 4. 可擴展添加集群模式下的尋址邏輯(CRC16槽位計算)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。