Compare commits

...

2 Commits

Author SHA1 Message Date
HuangJiaLuo 0bcf214080 feat(lru): feat lru clean 2021-10-05 19:28:53 +08:00
HuangJiaLuo 54f80ae1f3 feat(lru): feat lru clean 2021-10-05 19:25:36 +08:00
2 changed files with 36 additions and 1 deletions

View File

@ -95,12 +95,17 @@ func (lru *SingleCache) Add(key string, val structure.KeyBaseInterface) {
if elVal, ok := lru.lruMap[key]; ok {
lru.li.MoveToFront(elVal)
elVal.Value = keyBaseVal
err := lru.DelToClearSize()
if err != nil{
return
}
return
}
valEl := lru.li.PushFront(keyBaseVal)
lru.lruMap[key] = valEl
//增加大小
lru.UpdateLruSize(structure.UpdateLength(valEl.Value.(*keyBaseValue).val.SizeByte()))
lru.DelToClearSize()
}
// Get 查找key对应的value
@ -128,3 +133,17 @@ func (lru *SingleCache) Del() error {
lru.li.Remove(data)
return nil
}
//DelToClearSize 删除至清理长度大小
func (lru *SingleCache) DelToClearSize() error {
for {
if lru.nowSize > (4/3) * lru.clearSize{
err := lru.Del()
if err != nil{
return err
}
} else {
return nil
}
}
}

View File

@ -20,5 +20,21 @@ func TestNewLRUCache(t *testing.T) {
cache.Del()
fmt.Println(cache.nowSize)
_, isTrue := cache.Get("1")
require.Equal(t, isTrue, true)
require.Equal(t, isTrue, false)
}
func TestSingleCache_DelToClearSize(t *testing.T) {
cache := NewLRUCache()
v1 := stringx.NewStringSingle()
v2 := stringx.NewStringSingle()
//v3 := stringx.NewStringSingle()
//v4 := stringx.NewStringSingle()
cache.Add("1", v1)
cache.Add("2", v2)
res, ok := cache.Get("1")
if ok {
fmt.Println(res)
}
_, ok = cache.Get("1")
require.Equal(t, ok, false)
}