关于redis:redis源码字典

5次阅读

共计 1214 个字符,预计需要花费 4 分钟才能阅读完成。

1. 简介
字典应用哈希表作为底层实现,一个字典里蕴含 2 个哈希表,一个 ht[0]是失常状况下应用,ht[1]会在 rehash 的时候应用,一个哈希表蕴含多个哈希表节点,每个哈希表节点保留了字典中的一个键值对。Redis 中的数据库就是应用字典来作为底层实现。

2. 结构图(一般状态下没有进行 rehash 的状况)

/*
 * 字典
 */
typedef struct dict {

    // 类型特定函数
    dictType *type;

    // 公有数据
    void *privdata;

    // 哈希表
    dictht ht[2];

    // rehash 索引
    // 当 rehash 不在进行时,值为 -1
    int rehashidx; /* rehashing not in progress if rehashidx == -1 */

    // 目前正在运行的平安迭代器的数量
    int iterators; /* number of iterators currently running */

} dict;

/* This is our hash table structure. Every dictionary has two of this as we
 * implement incremental rehashing, for the old to the new table. */
/*
 * 哈希表
 *
 * 每个字典都应用两个哈希表,从而实现渐进式 rehash。*/
typedef struct dictht {
    
    // 哈希表数组
    dictEntry **table;

    // 哈希表大小
    unsigned long size;
    
    // 哈希表大小掩码,用于计算索引值
    // 总是等于 size - 1
    unsigned long sizemask;

    // 该哈希表已有节点的数量
    unsigned long used;

} dictht;
/*
 * 哈希表节点
 */
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);

    // 复制键的函数
    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;
正文完
 0