package lru import ( "container/list" _ "gitee.com/timedb/wheatCache/conf" "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" ) type keyBaseValue struct { key string val structure.KeyBaseInterface } type singleCache struct { maxsize int64 //最大的长度 clearSize int64 // 清理长度 nowSize int64 // 现在的长度 li *list.List lruMap map[string]*list.Element lruDriver event.DriverInterface lruConsumer event.ConsumerInterface lruProduce event.ProduceInterface // 发送清理事件 } func (lru *singleCache) UpdateLruLength(length int64) { atomic.AddInt64(&lru.nowSize, length) } // NewLRUCache lru初始化 func NewLRUCache() *singleCache { maxSize := viper.GetString("lruCache.maxSize") clearSize := viper.GetString("lruCache.clearSize") maxDriver := viper.GetInt("lruCache.eventDriverSize") lruDriver := event.NewDriver(maxDriver) return &singleCache{ maxsize: util.ParseSizeToBit(maxSize), clearSize: util.ParseSizeToBit(clearSize), nowSize: 0, li: list.New(), lruMap: make(map[string]*list.Element), lruDriver: lruDriver, lruConsumer: event.NewConsumer(lruDriver), lruProduce: event.NewProduce(lruDriver), } } // RetDriver 获取驱动 func (lru *singleCache) RetDriver() event.DriverInterface { return lru.lruDriver } //Add 增加 func (lru *singleCache) Add(key string, val structure.KeyBaseInterface) { keyBaseVal := &keyBaseValue{ key: key, val: val, } if elVal, ok := lru.lruMap[key]; ok { lru.li.MoveToFront(elVal) elVal.Value = keyBaseVal return } valEl := lru.li.PushFront(keyBaseVal) lru.lruMap[key] = valEl } // Get 查找key对应的value func (lru *singleCache) Get(key string) (structure.KeyBaseInterface, bool) { if lru.lruMap == nil { return nil, false } if elVal, ok := lru.lruMap[key]; ok { lru.li.MoveToFront(elVal) return elVal.Value.(*keyBaseValue).val, true } return nil, false } //Del 删除机制 func (lru *singleCache) Del() error { if lru.lruMap == nil { return errorx.New("lru is nil") } data := lru.li.Back() delete(lru.lruMap, data.Value.(*keyBaseValue).key) lru.li.Remove(data) return nil }