本篇内容介绍了“Java中Redis的LRU缓存机制怎么实现”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

第一种实现(使用LinkedHashMap)

publicclassLRUCache{intcapacity;Map<Integer,Integer>map;publicLRUCache(intcapacity){this.capacity=capacity;map=newLinkedHashMap<>();}publicintget(intkey){//如果没有找到if(!map.containsKey(key)){return-1;}//找到了就刷新数据Integervalue=map.remove(key);map.put(key,value);returnvalue;}publicvoidput(intkey,intvalue){if(map.containsKey(key)){map.remove(key);map.put(key,value);return;}map.put(key,value);//超出capacity,删除最久没用的即第一个,或者可以复写removeEldestEntry方法if(map.size()>capacity){map.remove(map.entrySet().iterator().next().getKey());}}publicstaticvoidmain(String[]args){LRUCachelruCache=newLRUCache(10);for(inti=0;i<10;i++){lruCache.map.put(i,i);System.out.println(lruCache.map.size());}System.out.println(lruCache.map);lruCache.put(10,200);System.out.println(lruCache.map);}

第二种实现(双链表+hashmap)

publicclassLRUCache{privateintcapacity;privateMap<Integer,ListNode>map;privateListNodehead;privateListNodetail;publicLRUCache2(intcapacity){this.capacity=capacity;map=newHashMap<>();head=newListNode(-1,-1);tail=newListNode(-1,-1);head.next=tail;tail.pre=head;}publicintget(intkey){if(!map.containsKey(key)){return-1;}ListNodenode=map.get(key);node.pre.next=node.next;node.next.pre=node.pre;returnnode.val;}publicvoidput(intkey,intvalue){if(get(key)!=-1){map.get(key).val=value;return;}ListNodenode=newListNode(key,value);map.put(key,node);moveToTail(node);if(map.size()>capacity){map.remove(head.next.key);head.next=head.next.next;head.next.pre=head;}}//把节点移动到尾巴privatevoidmoveToTail(ListNodenode){node.pre=tail.pre;tail.pre=node;node.pre.next=node;node.next=tail;}//定义双向链表节点privateclassListNode{intkey;intval;ListNodepre;ListNodenext;//初始化双向链表publicListNode(intkey,intval){this.key=key;this.val=val;pre=null;next=null;}}}补充

像第一种方式,如果复写removeEldestEntry会更简单,这里简单的展示一下

publicclassLRUCacheextendsLinkedHashMap<Integer,Integer>{privateintcapacity;@OverrideprotectedbooleanremoveEldestEntry(Map.Entry<Integer,Integer>eldest){returnsize()>capacity;}}

“Java中Redis的LRU缓存机制怎么实现”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!