您好,登錄后才能下訂單哦!
這篇文章主要介紹“怎么實(shí)現(xiàn)Redis的LRU緩存機(jī)制”,在日常操作中,相信很多人在怎么實(shí)現(xiàn)Redis的LRU緩存機(jī)制問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”怎么實(shí)現(xiàn)Redis的LRU緩存機(jī)制”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!
第一種實(shí)現(xiàn)(使用LinkedHashMap)
public class LRUCache {
int capacity;
Map<Integer,Integer> map;
public LRUCache(int capacity){
this.capacity = capacity;
map = new LinkedHashMap<>();
}
public int get(int key){
//如果沒(méi)有找到
if (!map.containsKey(key)){
return -1;
}
//找到了就刷新數(shù)據(jù)
Integer value = map.remove(key);
map.put(key,value);
return value;
}
public void put(int key,int value){
if (map.containsKey(key)){
map.remove(key);
map.put(key,value);
return;
}
map.put(key,value);
//超出capacity,刪除最久沒(méi)用的即第一個(gè),或者可以復(fù)寫removeEldestEntry方法
if (map.size() > capacity){
map.remove(map.entrySet().iterator().next().getKey());
}
}
public static void main(String[] args) {
LRUCache lruCache = new LRUCache(10);
for (int i = 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);
}
第二種實(shí)現(xiàn)(雙鏈表+hashmap)
public class LRUCache {
private int capacity;
private Map<Integer,ListNode>map;
private ListNode head;
private ListNode tail;
public LRUCache2(int capacity){
this.capacity = capacity;
map = new HashMap<>();
head = new ListNode(-1,-1);
tail = new ListNode(-1,-1);
head.next = tail;
tail.pre = head;
}
public int get(int key){
if (!map.containsKey(key)){
return -1;
}
ListNode node = map.get(key);
node.pre.next = node.next;
node.next.pre = node.pre;
return node.val;
}
public void put(int key,int value){
if (get(key)!=-1){
map.get(key).val = value;
return;
}
ListNode node = new ListNode(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;
}
}
//把節(jié)點(diǎn)移動(dòng)到尾巴
private void moveToTail(ListNode node) {
node.pre = tail.pre;
tail.pre = node;
node.pre.next = node;
node.next = tail;
}
//定義雙向鏈表節(jié)點(diǎn)
private class ListNode{
int key;
int val;
ListNode pre;
ListNode next;
//初始化雙向鏈表
public ListNode(int key,int val){
this.key = key;
this.val = val;
pre = null;
next = null;
}
}
}
像第一種方式,如果復(fù)寫removeEldestEntry會(huì)更簡(jiǎn)單,這里簡(jiǎn)單的展示一下
public class LRUCache extends LinkedHashMap<Integer,Integer> {
private int capacity;
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity;
}
}
到此,關(guān)于“怎么實(shí)現(xiàn)Redis的LRU緩存機(jī)制”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。