四 redis內(nèi)存淘汰策略思想

目標

分析redis的內(nèi)存淘汰策略, lru算法簡介

lru算法簡介

Least recently used(LRU,最近最少使用):根據(jù)數(shù)據(jù)的歷史訪問記錄淘汰數(shù)據(jù)。

lru算法

緩存污染問題:對于業(yè)務系統(tǒng)的批量性操作造成部分數(shù)據(jù)臨時活躍度升高情況,造成這部分數(shù)據(jù)熱度極速增加,而批量操作完后,緩存數(shù)據(jù)將無用.

優(yōu)化---LRU-K算法

在LRU的基礎上,新增一個隊列,用來計算數(shù)據(jù)的訪問次數(shù),只有在一定時間閾值內(nèi)訪問次數(shù)達到K次的數(shù)據(jù),才會放到LRU隊列中,如圖


lru-k

redis淘汰策略

redis對于過期key的處理方式有兩種 分為2種:passive (被動)和active(主動):

  1. 被動--惰性刪除:當一些客戶端進行訪問的時候,發(fā)現(xiàn)key已超時過期,刪除此key

  2. 主動: 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

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容