|
|
|
@ -0,0 +1,101 @@
|
|
|
|
|
package lru
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"container/list"
|
|
|
|
|
"errors"
|
|
|
|
|
"gitee.com/timedb/wheatCache/pkg/structure"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// feat
|
|
|
|
|
/*
|
|
|
|
|
1. cleanProduce
|
|
|
|
|
2. 定义 LRUSingle Work 函数
|
|
|
|
|
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
type Node struct {
|
|
|
|
|
Key interface{}
|
|
|
|
|
value structure.KeyBaseInterface
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (*Node) NewCacheNode(k interface{}, v structure.KeyBaseInterface) *Node {
|
|
|
|
|
return &Node{Key: k, value: v}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type LRUCache struct {
|
|
|
|
|
maxsize int64 //最大的长度
|
|
|
|
|
clearsize int64 // 清理长度
|
|
|
|
|
nowsize int64 // 现在的长度
|
|
|
|
|
li *list.List
|
|
|
|
|
LruMap map[interface{}]*list.Element // TODO LRU 对外暴露
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// NewLRUCache lru初始化 TODO 单例模式
|
|
|
|
|
func NewLRUCache(msize, csize int64) *LRUCache {
|
|
|
|
|
return &LRUCache{
|
|
|
|
|
maxsize: msize,
|
|
|
|
|
clearsize: csize,
|
|
|
|
|
nowsize: 0,
|
|
|
|
|
li: list.New(),
|
|
|
|
|
LruMap: make(map[interface{}]*list.Element)}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Add 增 TODO 大问题
|
|
|
|
|
func (lru *LRUCache) Add(k interface{}, v structure.KeyBaseInterface) error {
|
|
|
|
|
|
|
|
|
|
if lru.li == nil {
|
|
|
|
|
return nil // TODO err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// TODO 封装 Key 迁移方法
|
|
|
|
|
if PreEle, ok := lru.LruMap[k]; ok {
|
|
|
|
|
lru.li.MoveToFront(PreEle)
|
|
|
|
|
PreEle.Value.(*Node).value = v
|
|
|
|
|
lru.nowsize += PreEle.Value.(*Node).value.SizeByte()
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// TODO 增加的情况下, 应该只维护 maxSize
|
|
|
|
|
if lru.nowsize >= lru.maxsize*1/3 {
|
|
|
|
|
lru.nowsize -= lru.maxsize
|
|
|
|
|
if PreEle, ok := lru.LruMap[k]; ok {
|
|
|
|
|
cacheNode := PreEle.Value.(*Node).value
|
|
|
|
|
delete(lru.LruMap, cacheNode.SizeByte())
|
|
|
|
|
lru.li.Remove(PreEle)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
newEle := lru.li.PushFront(&Node{k, v})
|
|
|
|
|
lru.LruMap[k] = newEle // TODO nil 指针
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Get 查 // TODO err
|
|
|
|
|
func (lru *LRUCache) Get(k interface{}) (v structure.KeyBaseInterface, ret bool) {
|
|
|
|
|
|
|
|
|
|
if lru.LruMap == nil {
|
|
|
|
|
return v, false
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if PreEle, ok := lru.LruMap[k]; ok {
|
|
|
|
|
// 移到最前面
|
|
|
|
|
lru.li.MoveToFront(PreEle)
|
|
|
|
|
return PreEle.Value.(*Node).value, true
|
|
|
|
|
}
|
|
|
|
|
return v, false
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Clear 删除 // TODO 方案不对
|
|
|
|
|
func (lru *LRUCache) Clear(k interface{}) error {
|
|
|
|
|
if lru.LruMap == nil {
|
|
|
|
|
return errors.New("cache 为空")
|
|
|
|
|
}
|
|
|
|
|
for lru.nowsize >= lru.clearsize*1/3 {
|
|
|
|
|
if PreEle, ok := lru.LruMap[k]; ok {
|
|
|
|
|
cacheNode := PreEle.Value.(*Node).value
|
|
|
|
|
delete(lru.LruMap, cacheNode)
|
|
|
|
|
lru.li.Remove(PreEle)
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|