问题
When in memcache the available memory is full, memcache uses the LRU (last recently used) algorithm to free memory. My question is will the LRU Algorithm rather delete entries that have not been used for some amount of time (last recently used) than expired items? Entries that are expiring are not deleted on that exact moment but when the next time someone tries to access it (AFAIR). So will the LRU Algorithm (also) account for the expiry of keys?
回答1:
To understand how memcached does LRU you must go deeper and understand how memcached stores items. Items are stored depending on their size, simply put all your items that are lets say 100k get stored in the same slab, while other items that are 200k are stored in a different slab.
When memory gets full and you try to store a 100k item, memcached will apply LRU on that slab. If there are keys expired or not used in the 200k slab, they remain there, while if the 100k slab has only hot keys, one of those based on the algorithm will be evicted.
Back to your question, when memory is full and you try to store an item, memcached will look first for expired items in the slab you are trying to write to, then look for the least used items. So yes, it does take into account the expiry of the keys, or better yet, expired keys go first before LRU.
Also, when you try to get an item which is past its expiration date, that item is evicted and the memory reclaimed.
More details on (lots on google for memcached memory allocation which explains LRU as well, so plenty to read on this):
http://returnfoo.com/2012/02/memcached-memory-allocation-and-optimization-2/
http://www.adayinthelifeof.nl/2011/02/06/memcache-internals/
And a really nice tool which I recommend on every memcached topic :
http://code.google.com/p/phpmemcacheadmin/
Hope it helps!
回答2:
From what I know this statement is not true.
"Back to your question, when memory is full and you try to store an item, memcached will look first for expired items in the slab you are trying to write to, then look for the least used items. So yes, it does take into account the expiry of the keys, or better yet, expired keys go first before LRU."
Memcache will evict item according to LRU (it doesn't matter if it has any expired items as long as they are more recently used than another key (even valid)).
Tested a while ago on Memcache 1.4.4.
来源:https://stackoverflow.com/questions/10122384/will-the-lru-delete-entries-that-have-not-been-used-for-some-amount-of-time