Golang Gcache中的LRU和LFU

源碼:https://github.com/bluele/gcache

一、LRU
    SET
    GET
    DELETE
    Loader
二、LFU
    SET
    GET
    DELETE
    Loader
  1. 多種淘汰策略,LRU、LFU、simple;
  2. 提供loder,singleflight方式;
  3. 時間窗口的概念是通過整個cache表的過期時間來實現的;
  4. 過期刪除,訪問時才被刪除;
  5. 過期和淘汰策略是分開的:訪問過期會刪除,添加元素會淘汰(淘汰時不看過期時間);
  6. LRU/LFU更新記錄時開銷O(1),假如用堆之類相比開銷很大;

大鎖的改進:
讀寫鎖
鎖的粒度,整個map,單獨item
鎖的實現:CAS

一、LRU

LRU淘汰的思想是近期不被訪問的元素,在未來也不太會被訪問,時間的局部性。
缺點就是低頻、偶發的訪問會干擾,因為訪問一次就會被放在最熱,“容錯性”較差。

// Discards the least recently used items first.
type LRUCache struct {
   baseCache
   items     map[interface{}]*list.Element //k-(lruItem為value的鏈表節點)
   evictList *list.List. //維護順序的雙向鏈表
}

type lruItem struct {
   clock      Clock
   key        interface{}
   value      interface{}
   expiration *time.Time
}
SET

更新位置,更新value,更新時間
檢查淘汰,新增節點,更新時間;

// set a new key-value pair
func (c *LRUCache) Set(key, value interface{}) error {
   c.mu.Lock()
   defer c.mu.Unlock()
   _, err := c.set(key, value)
   return err
}

func (c *LRUCache) set(key, value interface{}) (interface{}, error) {
   var err error

   // Check for existing item
   var item *lruItem
   if it, ok := c.items[key]; ok {
      c.evictList.MoveToFront(it) //前置
      item = it.Value.(*lruItem)
      item.value = value 
   } else {
      // Verify size not exceeded
      if c.evictList.Len() >= c.size {
         c.evict(1)  //淘汰
      }
      item = &lruItem{
         clock: c.clock,
         key:   key,
         value: value,
      }
      c.items[key] = c.evictList.PushFront(item) //添加元素
   }

   //如果item沒有過期時間,就使用整個緩存的過期時間
   if c.expiration != nil {
      t := c.clock.Now().Add(*c.expiration)
      item.expiration = &t
   }

   if c.addedFunc != nil {
      c.addedFunc(key, value)
   }

   return item, nil
}


// Set a new key-value pair with an expiration time
func (c *LRUCache) SetWithExpire(key, value interface{}, expiration time.Duration) error {
   c.mu.Lock()
   defer c.mu.Unlock()
   item, err := c.set(key, value)
   if err != nil {
      return err
   }

   t := c.clock.Now().Add(expiration)
   item.(*lruItem).expiration = &t
   return nil
}

淘汰
鏈表的實現方便清除一個/多個;

// evict removes the oldest item from the cache.
func (c *LRUCache) evict(count int) {
   for i := 0; i < count; i++ {
      ent := c.evictList.Back()
      if ent == nil {
         return
      } else {
         c.removeElement(ent)
      }
   }
}
GET
// Get a value from cache pool using key if it exists.
// If it dose not exists key and has LoaderFunc,
// generate a value using `LoaderFunc` method returns value.
func (c *LRUCache) Get(key interface{}) (interface{}, error) {
   v, err := c.get(key, false)
   if err == KeyNotFoundError {
      return c.getWithLoader(key, true)
   }
   return v, err
}

func (c *LRUCache) getValue(key interface{}, onLoad bool) (interface{}, error) {
   c.mu.Lock()
   item, ok := c.items[key]
   if ok {  //命中緩存
      it := item.Value.(*lruItem)
      if !it.IsExpired(nil) { //沒有過期
         c.evictList.MoveToFront(item)  //更新順序
         v := it.value
         c.mu.Unlock()
         if !onLoad {
            c.stats.IncrHitCount()
         }
         return v, nil
      }
      //過期刪除
      c.removeElement(item)
   }
   c.mu.Unlock()
   if !onLoad {
      c.stats.IncrMissCount()
   }
   return nil, KeyNotFoundError
}
DELETE
// Remove removes the provided key from the cache.
func (c *LRUCache) Remove(key interface{}) bool {
   c.mu.Lock()
   defer c.mu.Unlock()

   return c.remove(key)
}

func (c *LRUCache) remove(key interface{}) bool {
   if ent, ok := c.items[key]; ok {
      c.removeElement(ent)
      return true
   }
   return false
}

func (c *LRUCache) removeElement(e *list.Element) {
   c.evictList.Remove(e)
   entry := e.Value.(*lruItem)
   delete(c.items, entry.key)
   if c.evictedFunc != nil {
      entry := e.Value.(*lruItem)
      c.evictedFunc(entry.key, entry.value)
   }
}
Loader
  1. 用戶提供loader方式,loaderExpireFunc可以基于key獲取到對應的value;
// Set a loader function.
// loaderFunc: create a new value with this function if cached value is expired.
func (cb *CacheBuilder) LoaderFunc(loaderFunc LoaderFunc) *CacheBuilder {
   cb.loaderExpireFunc = func(k interface{}) (interface{}, *time.Duration, error) {
      v, err := loaderFunc(k)
      return v, nil, err
   }
   return cb
}
  1. 提供統一的加載方法,使用singleflight,執行c.loaderExpireFunc(key)。
    此處提供了cb的封裝函數,可以針對獲取的value做不同的處理;比如直接返回用戶,或者加入緩存。
// load a new value using by specified key.
func (c *baseCache) load(key interface{}, cb func(interface{}, *time.Duration, error) (interface{}, error), isWait bool) (interface{}, bool, error) {
   v, called, err := c.loadGroup.Do(key, func() (v interface{}, e error) {
      defer func() {
         if r := recover(); r != nil {
            e = fmt.Errorf("Loader panics: %v", r)
         }
      }()
      return cb(c.loaderExpireFunc(key))
   }, isWait)
   if err != nil {
      return nil, called, err
   }
   return v, called, nil
}
  1. LRU的loder
func (c *LRUCache) getWithLoader(key interface{}, isWait bool) (interface{}, error) {
   if c.loaderExpireFunc == nil {
      return nil, KeyNotFoundError
   }
   value, _, err := c.load(key, func(v interface{}, expiration *time.Duration, e error) (interface{}, error) {
      if e != nil {
         return nil, e
      }
      c.mu.Lock()
      defer c.mu.Unlock()
      item, err := c.set(key, v)
      if err != nil {
         return nil, err
      }
      if expiration != nil {
         t := c.clock.Now().Add(*expiration)
         item.(*lruItem).expiration = &t
      }
      return v, nil
   }, isWait)
   if err != nil {
      return nil, err
   }
   return value, nil
}

二、LFU

LFU是基于訪問次數來淘汰元素,所以需要額外維護訪問次數的順序。

  1. 可以基于map+堆,但是堆的操作開銷是o(logn)的,開銷過大;


  2. 需要一種O(1)時間的LFU算法,論文:http://dhruvbird.com/lfu.pdf
    掛在次數為1的元素可以用鏈表實現,gcache使用的map簡單;
    用鏈表可以基于過期時間再排序,就是需要額外的開銷了。
// Discards the least frequently used items first.
type LFUCache struct {
   baseCache
   items    map[interface{}]*lfuItem
   freqList *list.List // list for freqEntry
}

type lfuItem struct {
   clock       Clock
   key         interface{}
   value       interface{}
   freqElement *list.Element
   expiration  *time.Time
}

//每個訪問次數單元,維護多個次數相同的lfuItem
type freqEntry struct {
   freq  uint
   items map[*lfuItem]struct{}
}
SET
// Set a new key-value pair with an expiration time
func (c *LFUCache) SetWithExpire(key, value interface{}, expiration time.Duration) error {
   c.mu.Lock()
   defer c.mu.Unlock()
   item, err := c.set(key, value)
   if err != nil {
      return err
   }

   t := c.clock.Now().Add(expiration)
   item.(*lfuItem).expiration = &t
   return nil
}

func (c *LFUCache) set(key, value interface{}) (interface{}, error) {
   var err error

   // Check for existing item
   item, ok := c.items[key]
   if ok {
      item.value = value
   } else {
      // Verify size not exceeded
      if len(c.items) >= c.size {
         c.evict(1)
      }
      item = &lfuItem{
         clock:       c.clock,
         key:         key,
         value:       value,
         freqElement: nil,
      }
      el := c.freqList.Front()
      fe := el.Value.(*freqEntry)
      fe.items[item] = struct{}{}

      item.freqElement = el
      c.items[key] = item
   }

   if c.expiration != nil {
      t := c.clock.Now().Add(*c.expiration)
      item.expiration = &t
   }

   if c.addedFunc != nil {
      c.addedFunc(key, value)
   }

   return item, nil
}

淘汰
淘汰的過程中,只是遍歷隨機淘汰,并不是按照過期時間;

// evict removes the least frequence item from the cache.
func (c *LFUCache) evict(count int) {
   entry := c.freqList.Front()
   for i := 0; i < count; {
      if entry == nil {
         return
      } else {
         for item, _ := range entry.Value.(*freqEntry).items {
            if i >= count {
               return
            }
            c.removeItem(item)
            i++
         }
         entry = entry.Next()
      }
   }
}
GET

過期刪除;
命中緩存,更新頻次;

// Get a value from cache pool using key if it exists.
// If it dose not exists key and has LoaderFunc,
// generate a value using `LoaderFunc` method returns value.
func (c *LFUCache) Get(key interface{}) (interface{}, error) {
   v, err := c.get(key, false)
   if err == KeyNotFoundError {
      return c.getWithLoader(key, true)
   }
   return v, err
}

func (c *LFUCache) getValue(key interface{}, onLoad bool) (interface{}, error) {
   c.mu.Lock()
   item, ok := c.items[key]
   if ok {
      if !item.IsExpired(nil) {
         c.increment(item)
         v := item.value
         c.mu.Unlock()
         if !onLoad {
            c.stats.IncrHitCount()
         }
         return v, nil
      }
      c.removeItem(item)
   }
   c.mu.Unlock()
   if !onLoad {
      c.stats.IncrMissCount()
   }
   return nil, KeyNotFoundError
}

頻次更新

func (c *LFUCache) increment(item *lfuItem) {
   currentFreqElement := item.freqElement //當前lfuItem對應的鏈表節點
   currentFreqEntry := currentFreqElement.Value.(*freqEntry)//當前鏈表節點的freqEntry
   nextFreq := currentFreqEntry.freq + 1 //計算頻次
   delete(currentFreqEntry.items, item) //當前freqEntry刪除這個lfuItem

   nextFreqElement := currentFreqElement.Next()//獲取下一個鏈表節點
   if nextFreqElement == nil {//創建新的節點,按頻次從小到大
      nextFreqElement = c.freqList.InsertAfter(&freqEntry{
         freq:  nextFreq,
         items: make(map[*lfuItem]struct{}),
      }, currentFreqElement)
   }
   nextFreqElement.Value.(*freqEntry).items[item] = struct{}{}//下一個freqEntry記錄lfuItem
   item.freqElement = nextFreqElement //lfuItem綁定到新的鏈表節點
}
DELETE
// Remove removes the provided key from the cache.
func (c *LFUCache) Remove(key interface{}) bool {
   c.mu.Lock()
   defer c.mu.Unlock()

   return c.remove(key)
}

func (c *LFUCache) remove(key interface{}) bool {
   if item, ok := c.items[key]; ok {
      c.removeItem(item)
      return true
   }
   return false
}

// removeElement is used to remove a given list element from the cache
func (c *LFUCache) removeItem(item *lfuItem) {
   delete(c.items, item.key)  //刪除map的關系
   delete(item.freqElement.Value.(*freqEntry).items, item) //刪除freq的關系
   if c.evictedFunc != nil {
      c.evictedFunc(item.key, item.value)
   }
}
Loader

LFU的loader跟LRU相同,加載數據,存入緩存。

func (c *LFUCache) getWithLoader(key interface{}, isWait bool) (interface{}, error) {
   if c.loaderExpireFunc == nil {
      return nil, KeyNotFoundError
   }
   value, _, err := c.load(key, func(v interface{}, expiration *time.Duration, e error) (interface{}, error) {
      if e != nil {
         return nil, e
      }
      c.mu.Lock()
      defer c.mu.Unlock()
      item, err := c.set(key, v)
      if err != nil {
         return nil, err
      }
      if expiration != nil {
         t := c.clock.Now().Add(*expiration)
         item.(*lfuItem).expiration = &t
      }
      return v, nil
   }, isWait)
   if err != nil {
      return nil, err
   }
   return value, nil
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,533評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,055評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,365評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,561評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,346評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,889評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,978評論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,118評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,637評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,558評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,739評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,246評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,980評論 3 346
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,362評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,619評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,347評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,702評論 2 370