Skip to content

Commit

Permalink
Refactor cache
Browse files Browse the repository at this point in the history
Signed-off-by: David Kröll <[email protected]>
  • Loading branch information
davidkroell committed Mar 16, 2019
1 parent abe46a4 commit acf743a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 18 deletions.
35 changes: 22 additions & 13 deletions cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,38 @@ 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 {
data interface{}
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 {
Expand Down Expand Up @@ -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
Expand All @@ -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
}
Expand Down
6 changes: 1 addition & 5 deletions models/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,14 @@ 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")
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)
Expand Down

0 comments on commit acf743a

Please sign in to comment.