feat(lru): feat lru clean

This commit is contained in:
HuangJiaLuo 2021-10-05 19:25:36 +08:00
parent 5292163b14
commit 54f80ae1f3
2 changed files with 59 additions and 26 deletions

View File

@ -6,8 +6,6 @@ import (
"gitee.com/timedb/wheatCache/pkg/errorx"
"gitee.com/timedb/wheatCache/pkg/event"
"gitee.com/timedb/wheatCache/pkg/structure"
"gitee.com/timedb/wheatCache/pkg/util"
"github.com/spf13/viper"
"sync/atomic"
)
@ -34,29 +32,29 @@ func (lru *SingleCache) UpdateLruSize(length structure.UpdateLength) {
}
func cacheInit() (int64, int64, int) {
maxSize := viper.GetString("lruCache.maxSize")
retMaxSize, maxErr := util.ParseSizeToBit(maxSize)
if maxErr != nil {
return 0, 0, 0
}
if retMaxSize == 0 {
retMaxSize = lruMaxSize
}
clearSize := viper.GetString("lruCache.clearSize")
retClearSize, clearErr := util.ParseSizeToBit(clearSize)
if clearErr != nil {
return 0, 0, 0
}
if retClearSize == 0 {
retClearSize = lruClearSize
}
maxDriver := viper.GetInt("lruCache.eventDriverSize")
if maxDriver == 0 {
maxDriver = lruEventDriver
}
return retMaxSize, retClearSize, maxDriver
//maxSize := viper.GetString("lruCache.maxSize")
//retMaxSize, maxErr := util.ParseSizeToBit(maxSize)
//if maxErr != nil {
// return 0, 0, 0
//}
//if retMaxSize == 0 {
// retMaxSize = lruMaxSize
//}
//
//clearSize := viper.GetString("lruCache.clearSize")
//retClearSize, clearErr := util.ParseSizeToBit(clearSize)
//if clearErr != nil {
// return 0, 0, 0
//}
//if retClearSize == 0 {
// retClearSize = lruClearSize
//}
//
//maxDriver := viper.GetInt("lruCache.eventDriverSize")
//if maxDriver == 0 {
// maxDriver = lruEventDriver
//}
return 30, 15, 2000
}
// NewLRUCache lru初始化
@ -95,12 +93,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 +131,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)
}