今天早上转载了NoSQLFan站点上的一篇:深入理解Redis主键失效原理及实现机制。写得很好,不过我个人感觉里面有一处没有讲清楚,主要是文章中的第三大点,“Memcached 删除失效主键的方法与 Redis 有何异同?”,有误导读者之嫌。读者第一眼看完,会形成一个印象:redis是没有LRU机制的,而Memcached是有的。这里我辩驳一下:

在Redis中,也是有LRU机制的,请参阅Redis作者的原博客:antirez weblog >> Redis as an LRU cache

原文中写得很清楚:

Another way to use Redis as a cache is the maxmemory directive, a feature that allows specifying a maximum amount of memory to use. When new data is added to the server, and the memory limit was already reached, the server will remove some old data deleting a volatile key, that is, a key with an EXPIRE (a timeout) set, even if the key is still far from expiring automatically.

在Redis服务器OOM的情况下,一旦有新的数据需要存储,LRU机制将会被启用,老的数据将会被删除,而这个删除的算法是什么,则可以在配置文件中设置:

# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
# is reached? You can select among five behavior:
#
# volatile-lru -> remove the key with an expire set using an LRU algorithm
# allkeys-lru -> remove any key accordingly to the LRU algorithm
# volatile-random -> remove a random key with 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 expire at all, just return an error on write operations