forked from p93542168/wheat-cache
Compare commits
2 Commits
master
...
feat-lru-c
Author | SHA1 | Date |
---|---|---|
HuangJiaLuo | 0bcf214080 | |
HuangJiaLuo | 54f80ae1f3 |
|
@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
Loading…
Reference in New Issue