返回

Redis 数据结构的底层实现

后端

RedisDB 结构

Redis 中存在“数据库”的概念,该结构由 redis.h 中的 redisDb 定义。当 Redis 服务器初始化时,会预先分配 16 个数据库,每个数据库都有自己的键空间,可以独立存储和管理数据。

typedef struct redisDb {
    dict *dict;             /* The keyspace for this DB */
    dict *expires;          /* A dictionary that holds expiring keys with their expire time */
    dict *blocking_keys;     /* A dictionary that holds keys with clients waiting for data (BLPOP) */
    dict *ready_keys;        /* A dictionary that holds keys with clients waiting for data (BRPOP) */
    dict *watched_keys;      /* A dictionary that holds the keys watched by clients */
    int id;                 /* Database ID */
    long long avg_ttl;        /* Average TTL of keys in the database */
} redisDb;

哈希表

Redis 中使用哈希表作为其基本数据结构之一,用于存储键值对。哈希表由 t_hashtable 结构定义,其中包含一个数组 table 和一个哈希函数 hashFunctiontable 数组存储哈希表中的元素,hashFunction 用于计算键的哈希值,并确定键在 table 数组中的位置。

typedef struct t_hashtable {
    void **table;              /* The array of elements */
    unsigned long size;        /* The size of the array */
    unsigned long used;        /* The number of elements in the array */
    hashFunction *hashFunction; /* The hash function to use */
} t_hashtable;

链表

链表是 Redis 中的另一个基本数据结构,用于存储有序的数据。链表由 list 结构定义,其中包含一个头结点 head 和一个尾结点 tail。头结点和尾结点都是哨兵节点,不包含实际数据,仅用于标记链表的开头和结尾。

typedef struct listNode {
    struct listNode *prev;
    struct listNode *next;
    void *value;
} listNode;

typedef struct list {
    listNode *head;
    listNode *tail;
} list;

字典

字典是 Redis 中使用的一种高级数据结构,用于存储键值对。字典由 dict 结构定义,其中包含一个哈希表 ht 和一个链表 keys。哈希表用于存储键值对,链表用于存储键的顺序。

typedef struct dict {
    t_hashtable ht[2];      /* The hash table */
    unsigned long size;      /* The size of the hash table */
    unsigned long used;      /* The number of elements in the hash table */
    unsigned char rehashidx; /* The index of the hash table to rehash */
    unsigned char rehashing; /* True if the hash table is being rehashed */
    list *keys;             /* A list of the keys in the hash table */
} dict;

集合

集合是 Redis 中一种无序的数据结构,用于存储唯一元素。集合由 set 结构定义,其中包含一个字典 dict。字典用于存储集合中的元素。

typedef struct set {
    dict dict;
} set;

有序集合

有序集合是 Redis 中一种有序的数据结构,用于存储具有分数的元素。有序集合由 zset 结构定义,其中包含一个字典 dict 和一个链表 skiplist。字典用于存储有序集合中的元素,链表用于存储元素的分数。

typedef struct zset {
    dict dict;
    zskiplist *zsl;
} zset;