From 1c2c0bb467325c5ae5209ca0521592c34f89e04f Mon Sep 17 00:00:00 2001 From: Piotr Biernat Date: Sun, 25 Jul 2021 01:44:50 +0200 Subject: [PATCH] [fix] Added GC to memory cache --- pkg/cache/memory_datastore.go | 20 ++++++++++++++++++++ pkg/cache/response.go | 2 +- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/pkg/cache/memory_datastore.go b/pkg/cache/memory_datastore.go index 7c2a997..9b5e065 100644 --- a/pkg/cache/memory_datastore.go +++ b/pkg/cache/memory_datastore.go @@ -11,25 +11,39 @@ package cache import ( "errors" + "time" ) +type TtlItem struct { + ts int // timestamp + ttl int +} + func NewMemoryDatastore() *MemoryDatastore { return &MemoryDatastore{ cache: make(map[string]interface{}), + ts: make(map[string]TtlItem), } } type MemoryDatastore struct { cache map[string]interface{} + ts map[string]TtlItem } func (ds *MemoryDatastore) SetKey(key string, data interface{}, ttl int) error { ds.cache[key] = data + ds.ts[key] = TtlItem{ + ts: time.Now().Second(), + ttl: ttl, + } return nil } func (ds *MemoryDatastore) GetKey(key string) (interface{}, error) { + ds.gc(key) // remove key is time of creation is outdated + if data, ok := ds.cache[key]; ok { return data, nil } @@ -40,3 +54,9 @@ func (ds *MemoryDatastore) GetKey(key string) (interface{}, error) { func (ds *MemoryDatastore) IsConnected() bool { return true } + +func (ds *MemoryDatastore) gc(key string) { + if item, ok := ds.ts[key]; ok && item.ts < time.Now().Second()-item.ttl { + delete(ds.cache, key) + } +} diff --git a/pkg/cache/response.go b/pkg/cache/response.go index 52562e4..2ea9d91 100644 --- a/pkg/cache/response.go +++ b/pkg/cache/response.go @@ -49,7 +49,7 @@ func (rm *ResponseCacheManager) Save(name string, r ResponseCache) bool { name = rm.prefix + name err = rm.datastore.SetKey(name, string(data), rm.ttl) if err != nil { - log.Println("Response-cache:", err, name) // FIXME + log.Println("Response-cache:", err, name) return false }