Redis 的数据清理策略详解
背景 摸清 Redis 的数据清理策略,给内存使用高的被动缓存场景,在遇到内存不足时 怎么做是最优解提供决策依据。 本文整理 Redis 的数据清理策略所有代码来自 Redis version : 5.x, 不同版本的 Redis 策略可能有调整 清理策略 Redis 的清理策略,总结概括为三点,被动清理、定时清理、驱逐清理 被动清理 访问 Key 时,每次都会检查该 Key 是否已过期,如果过期则删除该Key ,get 、scan 等指令都会触发 Key 的过期检查。 关键代码如下, expireIfNeeded(redisDb *db, robj *key) 函数会触发检查并删除 robj *lookupKeyReadWithFlags(redisDb *db, robj *key, int flags) { robj *val; if (expireIfNeeded(db,key) == 1) { /* Key expired. If we are in the context of a master, expireIfNeeded() * returns 0 o...