go 实现LRU算法

2023-01-28  本文已影响0人  wayyyy

本文转载自:动手写分布式缓存 - GeeCache第一天 LRU 缓存淘汰策略

缓存算法简介

内存是有限的,因此不可能无限制地添加数据。假定我们设置缓存能够使用的内存大小为 N,那么在某一个时间点,添加了某一条缓存记录之后,占用内存超过了 N,这个时候就需要从缓存中移除一条或多条数据了。那移除谁呢?我们肯定希望尽可能移除“没用”的数据,那如何判定数据“有用”还是“没用”呢?

LRU 算法实现

核心数据结构:


lru.png

这张图很好地表示了 LRU 算法最核心的 2 个数据结构

package lru

import "container/list"

type Value interface {
    Len() int
}

type entry struct {
    key   string
    value Value
}

type Cache struct {
    maxBytes  int64 // 缓存最大占用内存, 当为0时表示不作限制
    nBytes    int64 // 当前缓存已经占用的内存
    ll        *list.List
    cache     map[string]*list.Element
    OnEvicted func(key string, value Value) // 被淘汰时的回调函数
}

func NewCache(maxBytes int64, onEvicted func(string, Value)) *Cache {
    return &Cache{
        maxBytes:  maxBytes,
        ll:        list.New(),
        cache:     make(map[string]*list.Element),
        OnEvicted: onEvicted,
    }
}

func (c *Cache) Len() int {
    return c.ll.Len()
}

func (c *Cache) Get(key string) (value Value, exist bool) {
    elem, exist := c.cache[key]
    if exist {
        c.ll.MoveToFront(elem)
        kv := elem.Value.(*entry)
        return kv.value, true
    }

    return
}

func (c *Cache) Add(key string, value Value) {
    elem, exist := c.cache[key]
    if exist {
        c.ll.MoveToFront(elem)
        kv := elem.Value.(*entry)
        c.nBytes += int64(value.Len()) - int64(kv.value.Len())
        kv.value = value
    } else {
        elem := c.ll.PushFront(&entry{key, value})
        c.cache[key] = elem
        c.nBytes += int64(len(key)) + int64(value.Len())
    }

    for c.maxBytes != 0 && c.maxBytes < c.nBytes {
        c.removeOldest()
    }
}

func (c *Cache) removeOldest() {
    elem := c.ll.Back()
    if elem != nil {
        c.ll.Remove(elem)
        kv := elem.Value.(*entry)
        delete(c.cache, kv.key)
        c.nBytes = int64(len(kv.key)) + int64(kv.value.Len())
        if c.OnEvicted != nil {
            c.OnEvicted(kv.key, kv.value)
        }
    }
}

测试代码:

package lru

import (
    "reflect"
    "testing"
)

type String string

func (d String) Len() int {
    return len(d)
}

func TestGet(t *testing.T) {
    lru := NewCache(int64(0), nil)
    lru.Add("key1", String("1234"))
    if v, ok := lru.Get("key1"); !ok || string(v.(String)) != "1234" {
        t.Fatalf("cache hit key1=1234 failed")
    }
    if _, ok := lru.Get("key2"); ok {
        t.Fatalf("cache miss key2 failed")
    }
}

func TestRemoveoldest(t *testing.T) {
    k1, k2, k3 := "key1", "key2", "k3"
    v1, v2, v3 := "value1", "value2", "v3"
    cap := len(k1 + k2 + v1 + v2)
    lru := NewCache(int64(cap), nil)
    lru.Add(k1, String(v1))
    lru.Add(k2, String(v2))
    lru.Add(k3, String(v3))

    if _, ok := lru.Get("key1"); ok || lru.Len() != 2 {
        t.Fatalf("Removeoldest key1 failed")
    }
}

func TestOnEvicted(t *testing.T) {
    keys := make([]string, 0)
    callback := func(key string, value Value) {
        keys = append(keys, key)
    }
    lru := NewCache(int64(10), callback)
    lru.Add("key1", String("123456"))
    lru.Add("k2", String("k2"))
    lru.Add("k3", String("k3"))
    lru.Add("k4", String("k4"))

    expect := []string{"key1", "k2"}

    if !reflect.DeepEqual(expect, keys) {
        t.Fatalf("Call OnEvicted failed, expect keys equals to %s", expect)
    }
}

func TestAdd(t *testing.T) {
    lru := NewCache(int64(0), nil)
    lru.Add("key", String("1"))
    lru.Add("key", String("111"))

    if lru.nBytes != int64(len("key")+len("111")) {
        t.Fatal("expected 6 but got", lru.nBytes)
    }
}
上一篇 下一篇

猜你喜欢

热点阅读