From 75e1251d2221a9ad307d6c9315fed648d94ae779 Mon Sep 17 00:00:00 2001 From: HuangJiaLuo <1820799930@qq.com> Date: Mon, 4 Oct 2021 16:23:37 +0800 Subject: [PATCH] feat(lru): feat the init cache --- pkg/lru/lru.go | 39 +++++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/pkg/lru/lru.go b/pkg/lru/lru.go index d8703f5..d2b8d57 100644 --- a/pkg/lru/lru.go +++ b/pkg/lru/lru.go @@ -2,6 +2,7 @@ package lru import ( "container/list" + "fmt" _ "gitee.com/timedb/wheatCache/conf" "gitee.com/timedb/wheatCache/pkg/errorx" "gitee.com/timedb/wheatCache/pkg/event" @@ -11,7 +12,6 @@ import ( "sync/atomic" ) - type keyBaseValue struct { key string val structure.KeyBaseInterface @@ -29,35 +29,46 @@ type singleCache struct { lruProduce event.ProduceInterface // 发送清理事件 } +// UpdateLruLength 更新现在的长度 func (lru *singleCache) UpdateLruLength(length int64) { atomic.AddInt64(&lru.nowSize, length) } func cacheInit() (string, string, event.DriverInterface) { + viper.Set("lruCache.maxSize", "1GB") + viper.Set("lruCache.clearSize", "512MB") + viper.Set("lruCache.eventDriverSize", 2000) maxSize := viper.GetString("lruCache.maxSize") clearSize := viper.GetString("lruCache.clearSize") maxDriver := viper.GetInt("lruCache.eventDriverSize") lruDriver := event.NewDriver(maxDriver) + fmt.Println(clearSize) return maxSize, clearSize, lruDriver } // NewLRUCache lru初始化 func NewLRUCache() *singleCache { - maxSize, clearSize, lruDriver := cacheInit() - 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), - } + + lruCacheOnce.Do(func() { + maxSize, clearSize, lruDriver := cacheInit() + lru := &singleCache{ + maxsize: util.ParseSizeToBit(maxSize).(int64), + clearSize: util.ParseSizeToBit(clearSize).(int64), + nowSize: 0, + li: list.New(), + lruMap: make(map[string]*list.Element), + lruDriver: lruDriver, + lruConsumer: event.NewConsumer(lruDriver), + lruProduce: event.NewProduce(lruDriver), + } + lruCache = lru + go lru.lruSingleWork() + }) + return lruCache } -// RetDriver 获取驱动 -func (lru *singleCache) RetDriver() event.DriverInterface { +// GetDriver 获取驱动 +func (lru *singleCache) GetDriver() event.DriverInterface { return lru.lruDriver }