目標
分析redis的內(nèi)存淘汰策略, lru算法簡介
lru算法簡介
Least recently used(LRU,最近最少使用):根據(jù)數(shù)據(jù)的歷史訪問記錄淘汰數(shù)據(jù)。

緩存污染問題:對于業(yè)務系統(tǒng)的批量性操作造成部分數(shù)據(jù)臨時活躍度升高情況,造成這部分數(shù)據(jù)熱度極速增加,而批量操作完后,緩存數(shù)據(jù)將無用.
優(yōu)化---LRU-K算法
在LRU的基礎上,新增一個隊列,用來計算數(shù)據(jù)的訪問次數(shù),只有在一定時間閾值內(nèi)訪問次數(shù)達到K次的數(shù)據(jù),才會放到LRU隊列中,如圖

redis淘汰策略
redis對于過期key的處理方式有兩種 分為2種:passive (被動)和active(主動):
被動--惰性刪除:當一些客戶端進行訪問的時候,發(fā)現(xiàn)key已超時過期,刪除此key
主動: Redis 每秒運行10次會定時檢查操作,從相關的過期key集合中隨機測試20個key,刪除所有已過期的key,如果有超過25%的key過期,就再執(zhí)行一次此操作
但因為redis完全基于內(nèi)存操作的,很容易出現(xiàn)內(nèi)存不足的情況,此時可能內(nèi)存中又存有大量無用或命中率不高的緩存數(shù)據(jù),所以redis提供相應的內(nèi)存回收策略,如下配置:
# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
# is reached. You can select among five behaviors:
#最大內(nèi)存策略:當?shù)竭_最大使用內(nèi)存時,你可以在下面5種行為中選擇,Redis如何選擇淘汰數(shù)據(jù)庫鍵
#當內(nèi)存不足以容納新寫入數(shù)據(jù)時
# volatile-lru -> remove the key with an expire set using an LRU algorithm
# volatile-lru :在設置了過期時間的鍵空間中,移除最近最少使用的key。這種情況一般是把 redis 既當緩存,又做持久化存儲的時候才用。
# allkeys-lru -> remove any key according to the LRU algorithm
# allkeys-lru : 移除最近最少使用的key (推薦)
# volatile-random -> remove a random key with an expire set
# volatile-random : 在設置了過期時間的鍵空間中,隨機移除一個鍵,不推薦
# allkeys-random -> remove a random key, any key
# allkeys-random : 直接在鍵空間中隨機移除一個鍵,弄啥叻
# volatile-ttl -> remove the key with the nearest expire time (minor TTL)
# volatile-ttl : 在設置了過期時間的鍵空間中,有更早過期時間的key優(yōu)先移除 不推薦
# noeviction -> don't expire at all, just return an error on write operations
# noeviction : 不做過鍵處理,只返回一個寫操作錯誤。 不推薦
# Note: with any of the above policies, Redis will return an error on write
# operations, when there are no suitable keys for eviction.
# 上面所有的策略下,在沒有合適的淘汰刪除的鍵時,執(zhí)行寫操作時,Redis 會返回一個錯誤。下面是寫入命令:
# At the date of writing these commands are: set setnx setex append
# incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd
# sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby
# zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby
# getset mset msetnx exec sort
# 過期策略默認是:
# The default is:
# maxmemory-policy noeviction
參考博客:
https://blog.csdn.net/love254443233/article/details/82598381
https://blog.csdn.net/weixin_39982274/article/details/79276455
https://www.cnblogs.com/junyuhuang/p/5805168.html
https://www.cnblogs.com/junyuhuang/p/5993612.html
https://blog.csdn.net/qq_28018283/article/details/80764518
https://blog.csdn.net/qq_38423105/article/details/82720956