Redis內(nèi)存淘汰和過期刪除策略原理分析
Redis是一個內(nèi)存鍵值對數(shù)據(jù)庫,所以對于內(nèi)存的管理尤為重要。Redis內(nèi)部對于內(nèi)存的管理主要包含兩個方向,過期刪除策略和數(shù)據(jù)淘汰策略。思考:
- 什么是數(shù)據(jù)淘汰?
- 數(shù)據(jù)過期和數(shù)據(jù)淘汰都是刪除數(shù)據(jù),兩者有什么區(qū)別?
- 實際使用場景是多樣化的,如何選擇合適的淘汰策略?
淘汰策略原理
所謂數(shù)據(jù)淘汰是指在Redis內(nèi)存使用達到一定閾值的時候,執(zhí)行某種策略釋放內(nèi)存空間,以便于接收新的數(shù)據(jù)。內(nèi)存可使用空間由配置參數(shù)maxmemory決定(單位mb/GB)。故又叫"最大內(nèi)存刪除策略",也叫"緩存刪除策略"。
maxmemory配置
# 客戶端命令方式配置和查看內(nèi)存大小
127.0.0.1:6379> config get maxmemory
"maxmemory"
"0"
127.0.0.1:6379> config set maxmemory 100mb
OK
127.0.0.1:6379> config get maxmemory
"maxmemory"
"104857600"
#通過redis.conf 配置文件配置
127.0.0.1:6379> info
# Server
#...
# 配置文件路徑
config_file:/opt/homebrew/etc/redis.conf
#...
# 修改內(nèi)存大小
> vim /opt/homebrew/etc/redis.conf
############################## MEMORY MANAGEMENT ################################
# Set a memory usage limit to the specified amount of bytes.
# When the memory limit is reached Redis will try to remove keys
# according to the eviction policy selected (see maxmemory-policy).
#
#...
maxmemory 100mb
#...
注:若`maxmemory=0`則表示不做內(nèi)存限制,但是對于windows系統(tǒng)來說,32位系統(tǒng)默認可使用空間是3G,因為整個系統(tǒng)內(nèi)存是4G,需要留1G給系統(tǒng)運行。且淘汰策略會自動設置為noeviction,即不開啟淘汰策略,當使用空間達到3G的時候,新的內(nèi)存請求會報錯。
淘汰策略分類
- 淘汰策略配置maxmemory-policy,表示當內(nèi)存達到maxmemory時,將執(zhí)行配置的淘汰策略,由redis.c/freeMemoryIfNeeded 函數(shù)實現(xiàn)數(shù)據(jù)淘汰邏輯。maxmemory-policy配置
# 命令行配置方式
127.0.0.1:6379> CONFIG GET maxmemory-policy
"maxmemory-policy"
"noeviction"
127.0.0.1:6379> CONFIG SET maxmemory-policy volatile-lru
OK
127.0.0.1:6379> CONFIG GET maxmemory-policy
"maxmemory-policy"
"volatile-lru"
#redis.conf文件配置方式
# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
# is reached. You can select one from the following behaviors:
#
# volatile-lru -> Evict using approximated LRU, only keys with an expire set.
# allkeys-lru -> Evict any key using approximated LRU.
# volatile-lfu -> Evict using approximated LFU, only keys with an expire set.
# allkeys-lfu -> Evict any key using approximated LFU.
# volatile-random -> Remove a random key having an expire set.
# allkeys-random -> Remove a random key, any key.
# volatile-ttl -> Remove the key with the nearest expire time (minor TTL)
# noeviction -> Don't evict anything, just return an error on write operations.
#
# LRU means Least Recently Used
# LFU means Least Frequently Used
#
# Both LRU, LFU and volatile-ttl are implemented using approximated
# randomized algorithms.
# The default is:
# ...
maxmemory-policy noeviction
freeMemoryIfNeeded邏輯處理
int freeMemoryIfNeeded(void) {
size_t mem_used, mem_tofree, mem_freed;
int slaves = listLength(server.slaves);
/* Remove the size of slaves output buffers and AOF buffer from the count of used memory.*/
// 計算出 Redis 目前占用的內(nèi)存總數(shù),但有兩個方面的內(nèi)存不會計算在內(nèi):
// 1)從服務器的輸出緩沖區(qū)的內(nèi)存
// 2)AOF 緩沖區(qū)的內(nèi)存
mem_used = zmalloc_used_memory();
if (slaves) {
listIter li;
listNode *ln;
listRewind(server.slaves,&li);
while((ln = listNext(&li))) {
redisClient *slave = listNodeValue(ln);
unsigned long obuf_bytes = getClientOutputBufferMemoryUsage(slave);
if (obuf_bytes > mem_used)
mem_used = 0;
else
mem_used -= obuf_bytes;
}
}
if (server.aof_state != REDIS_AOF_OFF) {
mem_used -= sdslen(server.aof_buf);
mem_used -= aofRewriteBufferSize();
}
/* Check if we are over the memory limit. */
// 如果目前使用的內(nèi)存大小比設置的 maxmemory 要小,那么無須執(zhí)行進一步操作
if (mem_used <= server.maxmemory) return REDIS_OK;
// 如果占用內(nèi)存比 maxmemory 要大,但是 maxmemory 策略為不淘汰,那么直接返回
if (server.maxmemory_policy == REDIS_MAXMEMORY_NO_EVICTION)
return REDIS_ERR; /* We need to free memory, but policy forbids. */
/* Compute how much memory we need to free. */
// 計算需要釋放多少字節(jié)的內(nèi)存
mem_tofree = mem_used - server.maxmemory;
// 初始化已釋放內(nèi)存的字節(jié)數(shù)為 0
mem_freed = 0;
// 根據(jù) maxmemory 策略,
// 遍歷字典,釋放內(nèi)存并記錄被釋放內(nèi)存的字節(jié)數(shù)
while (mem_freed < mem_tofree) {
int j, k, keys_freed = 0;
// 遍歷所有字典
for (j = 0; j < server.dbnum; j++) {
long bestval = 0; /* just to prevent warning */
sds bestkey = NULL;
dictEntry *de;
redisDb *db = server.db+j;
dict *dict;
if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM)
{
// 如果策略是 allkeys-lru 或者 allkeys-random
// 那么淘汰的目標為所有數(shù)據(jù)庫鍵
dict = server.db[j].dict;
} else {
// 如果策略是 volatile-lru 、 volatile-random 或者 volatile-ttl
// 那么淘汰的目標為帶過期時間的數(shù)據(jù)庫鍵
dict = server.db[j].expires;
}
// 跳過空字典
if (dictSize(dict) == 0) continue;
/* volatile-random and allkeys-random policy */
// 如果使用的是隨機策略,那么從目標字典中隨機選出鍵
if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM ||
server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_RANDOM)
{
de = dictGetRandomKey(dict);
bestkey = dictGetKey(de);
}
/* volatile-lru and allkeys-lru policy */
// 如果使用的是 LRU 策略,
// 那么從一集 sample 鍵中選出 IDLE 時間最長的那個鍵
else if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
{
struct evictionPoolEntry *pool = db->eviction_pool;
while(bestkey == NULL) {
evictionPoolPopulate(dict, db->dict, db->eviction_pool);
/* Go backward from best to worst element to evict. */
for (k = REDIS_EVICTION_POOL_SIZE-1; k >= 0; k--) {
if (pool[k].key == NULL) continue;
de = dictFind(dict,pool[k].key);
/* Remove the entry from the pool. */
sdsfree(pool[k].key);
/* Shift all elements on its right to left. */
memmove(pool+k,pool+k+1,
sizeof(pool[0])*(REDIS_EVICTION_POOL_SIZE-k-1));
/* Clear the element on the right which is empty since we shifted one position to the left. */
pool[REDIS_EVICTION_POOL_SIZE-1].key = NULL;
pool[REDIS_EVICTION_POOL_SIZE-1].idle = 0;
/* If the key exists, is our pick. Otherwise it is a ghost and we need to try the next element. */
if (de) {
bestkey = dictGetKey(de);
break;
} else {
/* Ghost... */
continue;
}
}
}
}
/* volatile-ttl */
// 策略為 volatile-ttl ,從一集 sample 鍵中選出過期時間距離當前時間最接近的鍵
else if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_TTL) {
for (k = 0; k < server.maxmemory_samples; k++) {
sds thiskey;
long thisval;
de = dictGetRandomKey(dict);
thiskey = dictGetKey(de);
thisval = (long) dictGetVal(de);
/* Expire sooner (minor expire unix timestamp) is better candidate for deletion */
if (bestkey == NULL || thisval < bestval) {
bestkey = thiskey;
bestval = thisval;
}
}
}
/* Finally remove the selected key. */
// 刪除被選中的鍵
if (bestkey) {
long long delta;
robj *keyobj = createStringObject(bestkey,sdslen(bestkey));
propagateExpire(db,keyobj);
// 計算刪除鍵所釋放的內(nèi)存數(shù)量
delta = (long long) zmalloc_used_memory();
dbDelete(db,keyobj);
delta -= (long long) zmalloc_used_memory();
mem_freed += delta;
// 對淘汰鍵的計數(shù)器增一
server.stat_evictedkeys++;
notifyKeyspaceEvent(REDIS_NOTIFY_EVICTED, "evicted",
keyobj, db->id);
decrRefCount(keyobj);
keys_freed++;
/* When the memory to free starts to be big enough, we may */
/* start spending so much time here that is impossible to */
/* deliver data to the slaves fast enough, so we force the */
/* transmission here inside the loop. */
if (slaves) flushSlavesOutputBuffers();
}
}
if (!keys_freed) return REDIS_ERR; /* nothing to free... */
}
return REDIS_OK;
}
8種淘汰策略
- Redis定義的策略常量(version < 4.0)
/* Redis maxmemory strategies */
#define REDIS_MAXMEMORY_VOLATILE_LRU 0
#define REDIS_MAXMEMORY_VOLATILE_TTL 1
#define REDIS_MAXMEMORY_VOLATILE_RANDOM 2
#define REDIS_MAXMEMORY_ALLKEYS_LRU 3
#define REDIS_MAXMEMORY_ALLKEYS_RANDOM 4
#define REDIS_MAXMEMORY_NO_EVICTION 5
#define REDIS_DEFAULT_MAXMEMORY_POLICY REDIS_MAXMEMORY_NO_EVICTION
3.0版本提供6種策略:
4.0以上版本增加兩種LFU策略:
volatile-lfu( REDIS_MAXMEMORY_VOLATILE_LFU): Evict using approximated LFU, only keys with an expire set -> 對配置了過期時間的key,淘汰最近使用頻率最少的數(shù)據(jù)。
allkeys-lfu(REDIS_MAXMEMORY_ALLKEYS_LFU): Evict any key using approximated LFU -> 對所有key,淘汰最近使用頻率最少的數(shù)據(jù)。
volatile-lru( REDIS_MAXMEMORY_VOLATILE_LRU): Evict using approximated LRU, only keys with an expire set -> 內(nèi)存不足時,對所有配置了過期時間的key,淘汰最近最少使用的數(shù)據(jù)。
allkeys-lru(REDIS_MAXMEMORY_ALLKEYS_LRU): Evict any key using approximated LRU -> 內(nèi)存不足時,對所有key,淘汰最近最少使用的數(shù)據(jù)。
volatile-random( REDIS_MAXMEMORY_VOLATILE_RANDOM): Remove a random key having an expire set -> 內(nèi)存不足時,對所有配置了過期時間的key,淘汰隨機數(shù)據(jù)。
allkeys-random(REDIS_MAXMEMORY_ALLKEYS_RANDOM): Remove a random key, any key -> 內(nèi)存不足時,對所有key,淘汰隨機數(shù)據(jù)。
volatile-ttl( REDIS_MAXMEMORY_VOLATILE_TTL): Remove the key with the nearest expire time (minor TTL) -> 內(nèi)存不足時,對所有配置了過期時間的key,淘汰最近將要過期的數(shù)據(jù)。
noeviction( REDIS_MAXMEMORY_NO_EVICTION): Don't evict anything, just return an error on write operations -> 不開啟淘汰策略,在不配置淘汰策略的情況下,maxmemory-policy默認等于該值。內(nèi)存不足時,會拋出異常,寫操作不可用。不同系統(tǒng)存在差異性-具體見?
淘汰策略的選擇
- 存在冷熱數(shù)據(jù)區(qū)別,即意味著訪問頻率存在較大差異,4.0及以上版本建議選擇allkeys-lfu策略,但要設置lfu-decay-time 計數(shù)衰減值,一般默認1,這樣可避免緩存污染現(xiàn)象;3.0及以下版本建議選擇allkeys-lru策略。LFU訪問計數(shù)衰減配置
# The counter decay time is the time, in minutes, that must elapse in order
# for the key counter to be divided by two (or decremented if it has a value
# less <= 10).
#
# The default value for the lfu-decay-time is 1. A special value of 0 means to
# decay the counter every time it happens to be scanned.
#
lfu-decay-time 1
- 若整體訪問頻率較為平衡,則可選擇allkeys-random策略隨機淘汰數(shù)據(jù)。
- 存在置頂數(shù)據(jù)(或者希望一些數(shù)據(jù)長期被保存) ,4.0及以上版本建議選擇volatile-lfu策略,3.0及以下版本建議選擇volatile-lru策略。對于需要置頂?shù)臄?shù)據(jù)不設置或者設置較長的過期時間,其他數(shù)據(jù)都設置小于該值的過期時間,以便淘汰非置頂數(shù)據(jù)。
- 若希望所有的數(shù)據(jù)可通過過期時間來判斷其順序,則可選擇volatile-ttl策略。
- 由于過期刪除策略的存在,對于過期時間的配置,存在額外的expires字典表,是會占用部分Redis內(nèi)存的。若希望內(nèi)存可以得到更加高效的利用,可選擇allkeys-lru/allkeys-lfu策略。
Redis在實現(xiàn)淘汰策略時為了更合理的利用內(nèi)存空間以及保證Redis的高性能,只是幾近于算法的實現(xiàn)機制,其會從性能和可靠性層面做出一些平衡,故并不是完全可靠的。因此我們在實際使用過程中,建議都配置過期時間,主動刪除那些不再使用的數(shù)據(jù),以保證內(nèi)存的高效使用。另外關于LRU和LFU算法,Redis內(nèi)部在數(shù)據(jù)結構和實現(xiàn)機制上都做了一定程度的適應性改造
過期策略原理分析
眾所周知,在Redis的實際使用過程中,為了讓可貴的內(nèi)存得到更高效的利用,我們提倡給每一個key配置合理的過期時間,以避免因內(nèi)存不足,或因數(shù)據(jù)量過大而引發(fā)的請求響應延遲甚至是不可用等問題。思考:
- key的刪除是實時的嗎?
- 是否存在并發(fā)和數(shù)據(jù)一致性問題?
- 內(nèi)存空間是有限的,除了過期策略,Redis還有什么其他保障?
過期Key刪除原理
過期時間底層原理
當key設置了過期時間,Redis內(nèi)部會將這個key帶上過期時間放入過期字典(expires)中,當進行查詢時,會先在過期字典中查詢是否存在該鍵,若存在則與當前UNIX時間戳做對比來進行過期時間判定。
過期時間配置命令如下(即EX|PX|EXAT|PXAT):
# expire: t秒后過期
expire key seconds
# pexpire: t毫秒后過期
pexpire key millseconds
# expireat: 到達具體的時間戳時過期,精確到秒
expireat key timestamp
# pexpireat: 到達具體的時間戳時過期,精確到毫秒
pexpire key millseconds
這四個命令看似有差異,但在RedisDb底層,最終都會轉(zhuǎn)換成pexpireat指令。內(nèi)部由db.c/expireGenericCommand函數(shù)實現(xiàn),對外由上面四個指令調(diào)用
//expire命令
void expireCommand(redisClient *c) {
expireGenericCommand(c,mstime(),UNIT_SECONDS);
}
//expireat命令
void expireatCommand(redisClient *c) {
expireGenericCommand(c,0,UNIT_SECONDS);
}
//pexpire命令
void pexpireCommand(redisClient *c) {
expireGenericCommand(c,mstime(),UNIT_MILLISECONDS);
}
//pexpireat命令
void pexpireatCommand(redisClient *c) {
expireGenericCommand(c,0,UNIT_MILLISECONDS);
}
/* This is the generic command implementation for EXPIRE, PEXPIRE, EXPIREAT
* and PEXPIREAT. Because the commad second argument may be relative or absolute
* the "basetime" argument is used to signal what the base time is (either 0
* for *AT variants of the command, or the current time for relative expires).
*/
void expireGenericCommand(redisClient *c, long long basetime, int unit) {
...
/* unix time in milliseconds when the key will expire. */
long long when;
...
//如果是秒轉(zhuǎn)換為毫秒
if (unit == UNIT_SECONDS) when *= 1000;
when += basetime;
...
}
- 過期字典內(nèi)部存儲結構:key表示一個指向具體鍵的指針,value是long類型的毫秒精度的UNIX時間戳。
- Rediskey過期時間內(nèi)部流程圖:
圖片
常見刪除方式
- 定時刪除:在寫入key之后,根據(jù)否配置過期時間生成特定的定時器,定時器的執(zhí)行時間就是具體的過期時間。用CPU性能換去內(nèi)存存儲空間——即用時間獲取空間
- 定期刪除:提供一個固定頻率的定時器,執(zhí)行時掃描所有的key進行過期檢查,滿足條件的就進行刪除。
- 惰性刪除:數(shù)據(jù)不做及時釋放,待下一次接收到讀寫請求時,先進行過期檢查,若已過期則直接刪除。用內(nèi)存存儲空間換取CPU性能——即用空間換取時間
刪除方式 | 優(yōu)點 | 缺點 |
定時刪除 | 能及時釋放內(nèi)存空間,不會產(chǎn)生滯留數(shù)據(jù) | 頻繁生成和銷毀定時器,非常損耗CPU性能,影響響應時間和指令吞吐量 |
定期刪除 | 固定的頻率進行過期檢查,對CPU交友好 | 1.數(shù)據(jù)量比較大的情況下,會因為全局掃描而損耗CPU性能,且主線程的阻塞會導致其他請求響應延遲。2.未能及時釋放內(nèi)存空間。3.數(shù)據(jù)已過期,但定時器未執(zhí)行時會導致數(shù)據(jù)不一致。 |
惰性刪除 | 節(jié)約CPU性能 | 當某些數(shù)據(jù)長時間無請求訪問時,會導致數(shù)據(jù)滯留,使內(nèi)存無法釋放,占用內(nèi)存空間,甚至坑導致內(nèi)存泄漏而引發(fā)服務不可用 |
Redis過期刪除策略
由上述三種常用的刪除方式對比結果可知,單獨的使用任何一種方式都不能達到比較理想的結果,因此Redis的作者在設計過期刪除策略的時候,結合了定期刪除與惰性刪除兩種方式來完成。
定期刪除:內(nèi)部通過redis.c/activeExpireCycle函數(shù),以一定的頻率運行,每次運行從數(shù)據(jù)庫中隨機抽取一定數(shù)量的key進行過期檢查,若檢查通過,則對該數(shù)據(jù)進行刪除。在2.6版本中,默認每秒10次,在2.8版本后可通過redis.config配置文件的hz屬性對頻率進行設置,,官方建議數(shù)值不要超過100,否則將對CPU性能有重大影響。
# The range is between 1 and 500, however a value over 100 is usually not
# a good idea. Most users should use the default of 10 and raise this up to
# 100 only in environments where very low latency is required.
hz 10
惰性刪除:內(nèi)部通過redis.c/expireIfNeeded函數(shù),在每次執(zhí)行讀寫操作指令之前,進行過期檢查。若已設置過期時間且已過期,則刪除該數(shù)據(jù)。
刪除方式 | 優(yōu)點 | 缺點 |
Redis定期刪除 | 避免了全局掃描,每次隨機抽取數(shù)據(jù)量較少,性能較穩(wěn)定,執(zhí)行頻率可配置;避免了惰性刪除低頻數(shù)據(jù)長時間滯留的問題 | 存在概率上某些數(shù)據(jù)一直沒被抽取的情況,導致數(shù)據(jù)滯留 |
Redis惰性刪除 | 解決了定期刪除可能導致的數(shù)據(jù)滯留現(xiàn)象,性能較高 | 低頻數(shù)據(jù)長時間無法釋放 |
總結:由表格可知,這兩種方式的結合,能很好的解決過期數(shù)據(jù)滯留內(nèi)存的問題,同時也很好的保證了數(shù)據(jù)的一致性,保證了內(nèi)存使用的高效與CPU的性能
過期刪除策略引起的臟讀現(xiàn)象
- 在單節(jié)點實例模式下,因為Redis是單線程模型,所以過期策略可以保證數(shù)據(jù)一致性。
- 在集群模式下,過期刪除策略會引起臟讀現(xiàn)象
數(shù)據(jù)的刪除在主庫執(zhí)行,從庫不會執(zhí)行。對于惰性刪除策略來說,3.2版本以前,從庫讀取數(shù)據(jù)時哪怕數(shù)據(jù)已過期還是會返回數(shù)據(jù),3.2版本以后,則會返回空。
對于定期刪除策略,由于只是隨機抽取了一定的數(shù)據(jù),此時已過期但未被命中刪除的數(shù)據(jù)在從庫中讀取會出現(xiàn)臟讀現(xiàn)象。
過期時間命令EX|PX,在主從同步時,因為同步需要時間,就會導致主從庫實際過期時間出現(xiàn)偏差。比如主庫設置過期時間60s,但同步全量花費了1分鐘,那么在從庫接收到命令并執(zhí)行之后,就導致從庫key的過期時間整體跨越了兩分鐘,而此時主庫在一分鐘之前數(shù)據(jù)就已經(jīng)過期了。EXAT|PXAT 命令來設置過期時間節(jié)點。這樣可避免增量同步的發(fā)生。但需注意主從服務器時間一致。
在實際使用過程中,過期時間配置只是一種常規(guī)手段,當key的數(shù)量在短時間內(nèi)突增,就有可能導致內(nèi)存不夠用。此時就需要依賴于Redis內(nèi)部提供的淘汰策略來進一步的保證服務的可用性。
結語
到這里,我們可得出一個結論:Redis的高性能不僅僅體現(xiàn)在單線程上,還在于內(nèi)存和數(shù)據(jù)管理的相輔相成上。除此之外,Redis的多樣化數(shù)據(jù)結構和vm體系也為其高性能提供了更加有力的支撐,后續(xù)我們可以一起研究學習。