Redis中控制逐出策略的实现(redis 逐出策略)

Redis is an open source, networked memory data structure store, widely used for distributed caching, database storage and message queueing. By taking advantage of the widely adopted key-value storage system, it can quickly process large amounts of data and mntn the high performance results. When the system’s memory gets too full and cannot be serviced by the memory avlable, it’s time to put into action eviction policies that control the ejection of entries from the data store.

There are two types of eviction strategies for Redis, which are based on the algorithms used. The first is known as the LFU (Least Frequently Used), and the second as the LRU (Least Recently Used). Both algorithms rely on information stored in memory such as the frequency of data access, time of the last access, data size, and so on, to determine the entry that should be evicted.

The LFU algorithm takes into account the frequency of access of keys. The least frequently accessed key will be identified and evicted first, so that newer entries can be cached. The following example shows a simple implementation of this algorithm:

// LFU eviction policy
FUNCTION evict_LFU() {
/* Use AE algorithm to traverse the list of keys and find the key which was accessed least frequently */
RedisModule_Scan aux;
RedisModule_InitScan(&aux);
long minval = INT_MAX;
const char* minkey;
while (RedisModule_Next(&aux,&minkey, &minval) == REDISMODULE_OK){
if (minval
minkeyval = minval;
}
}
RedisModule_FreeScan(&aux);
removeKey(minkey);
}

The LRU algorithm, on the other hand, takes into account the time of last access of keys. The least recently used key will be identified and evicted first. This algorithm is more accurate and precise in determining the entry that should be removed. The following example shows a simple implementation of this algorithm:

// LRU eviction policy
FUNCTION evict_LRU() {
/* Initialize an aux scan and LRU double link list */
RedisModule_Scan aux;
RedisModule_LRU *lru;
RedisModule_InitScan(&aux);
RedisModule_InitLRU(&lru);
while (RedisModule_Next(&aux, &key, &value) == REDISMODULE_OK) {
RedisModule_LRU_Update(lru, key);
}
RedisModule_FreeScan(&aux);
const char* minkey;
RedisModule_LRU_GetFirst(lru, &minkey);
removeKey(minkey);
}

Whichever eviction policy is used, the implementation of it is critical in ensuring that the system performs at optimum levels by intelligently managing the memory space. Furthermore, depending on the usage scenario, different eviction policies can be enabled or disabled to get the best performance out of Redis.


数据运维技术 » Redis中控制逐出策略的实现(redis 逐出策略)