redis是一个键值对数据库服务器,服务器中的每个数据库都由一个server.h/redisDb节后表示,其中dict字典保存了数据库中的所有键值对,这个字典被称为键空间。
- 键空间的键,字符串对象
- 键空间的值,任意一种redis对象
typedef struct redisDb {dict *dict; /* The keyspace for this DB */dict *expires; /* Timeout of keys with a timeout set */dict *blocking_keys; /* Keys with clients waiting for data (BLPOP)*/dict *ready_keys; /* Blocked keys that received a PUSH */dict *watched_keys; /* WATCHED keys for MULTI/EXEC CAS */int id; /* Database ID */long long avg_ttl; /* Average TTL, just for stats */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. */} redisDb;
redisDb中的expires字典保存了数据库中所有键的过期时间,被称为过期字典。
- 过期字典的键是一个指针,指向键空间中的某个见对象
- 过期字典的值是一个long long类型的证书,保存了键所指向的数据库键的过期时间-一个毫秒精度的UNIX时间戳
过期键的删除策略
一般有三种策略:
- 定时删除:在设置键的过期时间的同时,创建一个定时器,让定时器在键过期时间来临时,立即对键进行删除。对内存友好,CPU不友好。
- 惰性删除:放任过期键不管。每次从键空间中获取键时,检查键的过期时间,过期则删除,没有则返回。对内存不友好,CPU友好。
- 定期删除:每隔一段时间,程序对数据库进行一次检查,删除里面的过期键。
redis中实现了惰性删除和定期删除。
