redis 7.0.2数据结构源码
redis 数据结构源码
🔔 redis 7.0.2源码
redis默认初始化16个库,那么库数据结构是如何设计的?
server.h
// 库,可类似看做MySQL中的库
typedef struct redisDb {
dict *dict; //存储键值对(主要操作对象)
dict *expires;//存储设置了超时时间的键副本
dict *blocking_keys;// 存储处于阻塞状态的客户端信息
dict *ready_keys; // 存储因某些操作而处于就绪状态的键
dict *watched_keys;// 存储被监视的key
int id;// 库ID
long long avg_ttl; //平均TTL,仅用于统计
unsigned long expires_cursor; /* Cursor of the active expire cycle. */
list *defrag_later; /* List of key names to attempt to defrag one by one, gradually. */
clusterSlotToKeyMapping *slots_to_keys; /* Array of slots to keys. Only used in cluster mode (db 0). */
} redisDb
看看dict如何设计的
dict.h
// 字典,可类似看做MySQL中的表
struct dict {
dictType *type;
dictEntry **ht_table[2];//2条链表,ht_table[0]当前正在使用的hash,ht_table[1]空hash表
unsigned long ht_used[2];//
long rehashidx; //若为-1,则不进行重新整理数据
/* Keep small vars at end for optimal (minimal) struct padding */
int16_t pauserehash; /* If >0 rehashing is paused (<0 indicates coding error) */
signed char ht_size_exp[2]; /* exponent of size. (size = 1<<exp) */
};
//字典类型:用于实现hash表和集合等数据结构,这里面的都是函数指针
typedef struct dictType {
uint64_t (*hashFunction)(const void *key);
void *(*keyDup)(dict *d, const void *key);
void *(*valDup)(dict *d, const void *obj);
int (*keyCompare)(dict *d, const void *key1, const void *key2);
void (*keyDestructor)(dict *d, void *key);
void (*valDestructor)(dict *d, void *obj);
int (*expandAllowed)(size_t moreMem, double usedRatio);
/* Allow a dictEntry to carry extra caller-defined metadata. The
* extra memory is initialized to 0 when a dictEntry is allocated. */
size_t (*dictEntryMetadataBytes)(dict *d);
} dictType;
//字典条目,存储k-v对的基本数据结构,可类似看做MySQL中的行数据
typedef struct dictEntry {
void *key;
union {
void *val;
uint64_t u64;
int64_t s64;
double d;
} v;
//同一哈希桶中的下一个条目。 由此可看出dictEntry是单向链表
struct dictEntry *next;
void *metadata[];
} dictEntry;
dictEntry 的联合体v用于存放string,list,set,hash等数据结构
- 如果值是string或复杂数据类型(如set,hash,list等),则使用
void *val。 - 如果值是一个无符号64位整数,则使用
uint64_t u64。 - 如果值是有符号64位整数,则使用
int64_t s64。 - 如果值是一个双精度浮点数,则使用
double d。
本文来自博客园,作者:勤匠,转载请注明原文链接:https://www.cnblogs.com/JarryShu/articles/18320517

浙公网安备 33010602011771号