This commit is contained in:
HuangJiaLuo 2021-09-05 22:48:01 +08:00
parent f7abb56e92
commit ee8c3d42e8
1 changed files with 91 additions and 26 deletions

View File

@ -1,45 +1,110 @@
package lru package main
import ( import (
"container/list" "container/list"
"gitee.com/timedb/wheatCache/pkg/lru/define" "fmt"
) )
type CacheNode struct { type Node struct {
value int Key, Value interface{}
key string
} }
type Cache struct { func (*Node) NewCacheNode(k, v interface{}) *Node {
cache map[string]*list.Element return &Node{k, v}
}
type LRUCache struct {
maxsize int //最大的长度
li *list.List li *list.List
size int // LRU的长度 LruMap map[interface{}]*list.Element
MaxByte int64 // 允许的最大存储
NowByte int64 // 目前的存储
} }
// 创建一个LRU // lru初始化
func NewLRU() *Cache { func NewLRUCache(size int) *LRUCache {
return &Cache{ return &LRUCache{
MaxByte: define.MaxByte, maxsize: size,
size: 0, li: list.New(),
NowByte: 0, LruMap: make(map[interface{}]*list.Element)}
cache: make(map[string]*list.Element), }
//返回lru的长度
func (lru *LRUCache) GetSize() int {
return lru.li.Len()
}
//增
func (lru *LRUCache) Add(k, v interface{}) error {
if lru.li == nil {
return nil
} }
if PreEle, ok := lru.LruMap[k]; ok {
lru.li.MoveToFront(PreEle)
PreEle.Value.(*Node).Value = v
return nil
}
newEle := lru.li.PushFront(&Node{k, v})
lru.LruMap[k] = newEle
//超过最长就删
if lru.li.Len() > lru.maxsize {
// 去掉最后一个
last := lru.li.Back()
if last == nil {
return nil
}
Node := last.Value.(*Node)
delete(lru.LruMap, Node.Key)
lru.li.Remove(last)
}
return nil
} }
// //
func GetLRU() { func (lru *LRUCache) Get(k interface{}) (v interface{}, 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
} }
// //删
func (c *Cache) AddLRU(key string, value int) { func (lru *LRUCache) Remove(k interface{}) bool {
if lru.LruMap == nil {
c.size += 1 return false
}
if PreEle, ok := lru.LruMap[k]; ok {
cacheNode := PreEle.Value.(*Node)
delete(lru.LruMap, cacheNode.Key)
lru.li.Remove(PreEle)
return true
}
return false
} }
//获取链表长度 func main() {
func (c *Cache) GetLRULength() int { lru := NewLRUCache(3)
return c.size lru.Add(10, "test1")
lru.Add(20, "test2")
lru.Add(30, "test3")
v, ret := lru.Get(10)
if ret {
fmt.Println(v)
}
lru.Add(40, "test4")
v, ret = lru.Get(20)
if ret {
fmt.Println(v)
}
} }