資料結構與演算法 Redis中LRU演算法的基本思想

2021-09-21 06:04:05 字數 1454 閱讀 2361

lru(least recently used)是一種快取置換演算法。即在快取有限的情況下,如果有新的資料需要載入進快取,則需要將最不可能被繼續訪問的快取剔除掉。

下面總結一下核心操作的步驟:

class dlinkednode
lru cache

public class lrucache 

public int get(int key)

// move the accessed node to the head;

this.movetohead(node);

return node.value;

}public void set(int key, int value)

}else

}/**

* always add the new node right after head;

*/private void addnode(dlinkednode node)

/*** remove an existing node from the linked list.

*/private void removenode(dlinkednode node)

/*** move certain node in between to the head.

*/private void movetohead(dlinkednode node)

// pop the current tail.

private dlinkednode poptail()

}

首先redis並沒有使用雙向鍊錶實現乙個lru演算法。

redis整體上是乙個大的dict,key是乙個string,而value都會儲存為乙個robj(redisobject)。

在redis的dict中每次按key獲取乙個值的時候,都會呼叫lookupkey函式,如果配置使用了lru模式,該函式會更新value中的lru欄位為當前秒級別的時間戳。

redis3.0的lru實現演算法:

1.第一次隨機選取的key都會放入乙個pool中(pool的大小為16),pool中的key是按lru時間戳大小順序排列的。

2.接下來每次隨機選取的key的lru值必須小於pool中最小的lru才會繼續放入,直到將pool放滿。

3.放滿之後,每次如果有新的key需要放入,需要將pool中lru最大的乙個key取出。

4.需要淘汰的時候,直接從pool中選取乙個lru最小的值然後將其淘汰。

redis中的lru演算法實現

資料結構與演算法 演算法 演算法和資料結構

資料結構與演算法 演算法 好吧,在這裡,您被優秀或優秀的軟體開發人員所隔開。在這種情況下,我會告訴您一開始或至少在我的情況下,並且我知道大多數時候,對於我認識的大多數人,您會覺得自己是乙個無能的人或白痴。基本上,我怎麼可能不理解這一點,然後您會感到沮喪。在這種情況下,我會告訴您情況並不像您想的那麼糟...

redis 資料結構與物件

簡單說下redis的資料結構,這些在網上也都有很詳細的解釋,redis 設計與實現 這本書基於redis3.0的,但是現在已經5.0 了,所以有些資料結構發生了變化,其中我自己實現發現了一部分,可能還有沒發現的。慢慢實踐吧 簡單動態字串是在c語音傳統的字串基礎上構建的,其資料結構為 struct s...

Redis資料結構與物件

redis使用五種型別物件實現實現鍵值對資料庫 字串 列表 雜湊 集合 有序集合 列表編碼 ziplist或linkedlist 雜湊編碼 ziplist或hashtable 集合編碼 intset或hashtable 有序集合編碼 ziplist或skiplist struct sdshdr 二進...