develop-issue-4 #8

Merged
keedosn merged 3 commits from develop-issue-4 into develop 2021-07-25 21:10:30 +02:00
2 changed files with 21 additions and 1 deletions
Showing only changes of commit 1c2c0bb467 - Show all commits

View File

@ -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)
}
}

View File

@ -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
}