From acf743ad9ac841b748034b4fb8e84000a13373f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Kr=C3=B6ll?= Date: Sat, 16 Mar 2019 11:09:19 +0100 Subject: [PATCH] Refactor cache MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: David Kröll --- cache/cache.go | 35 ++++++++++++++++++++++------------- models/database.go | 6 +----- 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/cache/cache.go b/cache/cache.go index 2343002..62d8b1f 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -6,10 +6,20 @@ import ( ) type Cache struct { - mu sync.Mutex - items map[string]item - maxAccessCount uint - defaultAccessCount uint + mu sync.Mutex + items map[string]item + Config +} + +type Config struct { + DecrInterval time.Duration + MaxAccessCount, StartAccessCount uint +} + +var DefaultConfig = Config{ + DecrInterval: time.Minute, + MaxAccessCount: 30, + StartAccessCount: 5, } type item struct { @@ -17,18 +27,17 @@ type item struct { accessCount uint } -func New(decrInterval time.Duration, maxAccessCount, defaultAccessCount uint) *Cache { +func New(conf Config) *Cache { c := Cache{ - items: map[string]item{}, - maxAccessCount: maxAccessCount, - defaultAccessCount: defaultAccessCount, + items: map[string]item{}, + Config: conf, } - go c.manage(decrInterval) + go c.manage() return &c } -func (c *Cache) manage(decrInterval time.Duration) { - t := time.NewTicker(decrInterval) +func (c *Cache) manage() { + t := time.NewTicker(c.DecrInterval) for range t.C { c.mu.Lock() for k, v := range c.items { @@ -62,7 +71,7 @@ func (c *Cache) Set(k string, v interface{}, force bool) (success bool) { if _, ok := c.items[k]; (ok && force) || !ok { c.items[k] = item{ data: v, - accessCount: c.defaultAccessCount, + accessCount: c.StartAccessCount, } c.mu.Unlock() return true @@ -77,7 +86,7 @@ func (c *Cache) Get(k string) (v interface{}, found bool) { val, ok := c.items[k] if ok { - if val.accessCount < c.maxAccessCount { + if val.accessCount < c.MaxAccessCount { val.accessCount++ c.items[k] = val } diff --git a/models/database.go b/models/database.go index 3d3d90f..0852b36 100644 --- a/models/database.go +++ b/models/database.go @@ -13,7 +13,7 @@ import ( var db Database var singleton sync.Once -var cacher = cache.New(time.Minute, 30, 5) +var cacher = cache.New(cache.DefaultConfig) // ErrNotFound is an error, which is raised if no database entries are found var ErrNotFound = errors.New("not found") @@ -21,10 +21,6 @@ var ErrCredentialMismatch = errors.New("credentials do not match a user") var ErrJWT = errors.New("parsing of JWT failed") var ErrCache = errors.New("error in cache") -type Relateable interface { - LoadRelated() (err error) -} - // DBModel eases the handling of database-related structs type DBModel interface { Save() (err error)