redis database source - yaokun123/php-wiki GitHub Wiki

redis的数据库源码详解

server.h

typedef struct redisDb {
    dict *dict;                 /* The keyspace for this DB 数据库的键空间,键值对都存放在这里。*/
    dict *expires;              /* Timeout of keys with a timeout set 设置了过期时间的key集合*/
    dict *blocking_keys;        /* Keys with clients waiting for data (BLPOP) 客户端阻塞等待的key集合(BLPOP)*/
    dict *ready_keys;           /* Blocked keys that received a PUSH 已就绪的阻塞key集合(PUSH)*/
    dict *watched_keys;         /* WATCHED keys for MULTI/EXEC CAS 在事务中监控受监控的key集合*/
    int id;                     /* Database ID 数据库ID*/
    long long avg_ttl;          /* Average TTL, just for stats 平均ttl*/
} redisDb;


typedef struct dict {
    dictType *type;            //定义了一下函数,比如hash函数等
    void *privdata;            //
    dictht ht[2];              //hash table ht[0] ht[1]两个hash表,在rehash时候会用到第二个,一般情况下都是使用第一个
    long rehashidx; /* rehashing not in progress if rehashidx == -1 rehash的进度,hash槽的索引*/
    unsigned long iterators; /* number of iterators currently running */
} dict;



typedef struct dictType {
    uint64_t (*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(渐进式rehash), for the old to the new table. */
typedef struct dictht {
    dictEntry **table;               //指向hashtable的地址
    unsigned long size;              //hashtable size
    unsigned long sizemask;          //size-1: mod
    unsigned long used;              //hashtable有多少个元素
} dictht;




typedef struct dictEntry {
    void *key;                     //string sds
    union {
        void *val;                 //value->RedisObject
        uint64_t u64;
        int64_t s64;
        double d;
    } v;
    struct dictEntry *next;        //hash冲突时使用
} dictEntry;



typedef struct redisObject {
    unsigned type:4;        //对象(value)的类型,string,list,hash,set,zset
    unsigned encoding:4;    //不同对象底层有不同编码,可以使用object encoding查看
    unsigned lru:LRU_BITS; /* LRU time (relative to global lru_clock) or
                            * LFU data (least significant 8 bits frequency
                            * and most significant 16 bits decreas time). */
    int refcount;
    void *ptr;             //真正存放value的地方
} robj;