1删除过期数据我们可以在设置Redis元素时指定过期时间,那么Redis如何删除这些超时元素? Redis使用两种策略:常规删除和惰性删除。 (1)定期删除Redis,并定期检查哪个KEY过期,如果过期则将其删除。但是,让我们想象一个问题:如果Redis存储了大量的KEY,则仅检查超时将消耗资源并严重影响服务能力。为了解决这个问题,Redis不检查完整的KEY,而只检查部分,同时引入了惰性删除策略。 (2)延迟删除假定KEY1已过期,但由于尚未检查,因此尚未删除。然后当程序访问KEY1时,Redis将检查KEY1是否已过期,如果过期,则不返回值将其删除,这是延迟删除策略。结合常规删除和惰性删除这两种策略可以确保可以删除过期的数据。 2内存消除当内存不足时,Redis将选择一些要删除的缓存元素,那么将删除哪些元素?常见的内存消除策略如下:不驱逐禁止驱逐数据,新的写操作将报告错误。 volatile-lru从具有到期时间集的数据集中选择最近使用最少的数据。 Volatile-ttl选择具有到期时间集的数据集。消除过期数据volatile-random从设置了过期时间的数据集中选择任何数据消除allkeys-lru从数据集中选择最近使用最少的数据消除allkeys-random从数据集中选择任何数据消除LRU(最近最少使用)最近最少使用的策略是更常用的策略。我们使用JAVA代码来实现简单的LRU策略。代码原理并不复杂:使用链表存储元素,并且表的头存储最近访问的元素,因此存储的结果是在表末尾最早访问的结果。元素,表的头存储最近访问的元素,当超出链表的容量时,可以删除尾部元素。 / ** *元素对象* * * * /公共类CacheElement {私有字符串密钥;私有对象值;公共CacheElement(字符串键,对象值){this.key =键; this.value = value;} public String getKey(){return key;} public Object getValue(){return value;} @Override public String toString(){return“ Element [key =”; +键+“,值=” +值+“]”; }} / ** * LRU缓存策略* * * * //公共类LRUCache {private int容量;私有的LinkedListcache;公共LRUCache(int容量){this.capacity =容量; this.cache = new LinkedList& lt;& gt;();} / ** *获取缓存的元素* *找到该元素后,从原始位置删除该元素并将其插入到链接列表的开头(最近)* / public CacheElement get(String key){Iteratoriterator = cache.iterator(); while(iterator.hasNext()){CacheElement element = iterator.next();如果(element.getKey()。equals(key)){iterator.remove(); System.out.println(“到达元素=” +元素); put(element.getKey(),element.getValue()); return元素;}}返回null;} / ** *存储缓存元素* *将新元素插入链表的头部(最近)* / public boolean put(String key,Object value){Iteratoriterator = cache.iterator( ); while(iterator.hasNext()){CacheElement element = iterator.next();如果(element .getKey()。equals(key)){iterator.remove();如果(容量== cache.size()){CacheElement deleteElement = cache.removeLast(); System.out.println(“容量完全删除尾部元素=” + deleteElement);} CacheElement元素=新的CacheElement(键,值); cache.addFirst(element); System.out.println(“插入头元素=” +元素);返回布尔值。 TRUE;} @Override public String toString(){返回“ LRUCache [capacity =” +容量+“,缓存=” +快取+“]”; }} / ** * LRU测试实例* * @author微信官方帐户" IT Xu Fatty” * * /公共类TestCache {公共静态void main(String [] args){System.out.println(“ ==================存储缓存元素==== =============”); LRUCache缓存=新的LRUCache(2); CacheElement element0 = new CacheElement(“ k0&”,“ v0&”); CacheElement element1 = new CacheElement(“ k1”,“ v1”); CacheElement element2 = new CacheElement(“ k2”,“ v2”); cache.put(e lement0.getKey(),element0.getValue()); cache.put(element1.getKey(),element1.getValue()); cache.put(element2.getKey(),element2.getValue()); System.out .println(“ ===================获取缓存元素==================”) ; System.out。 println(C