toolbox/kvmemcache/cache.go

69 lines
1.2 KiB
Go
Raw Permalink Normal View History

2021-04-02 15:14:32 +00:00
package kvmemcache
import (
"container/list"
"sync"
"time"
"git.crumpington.com/public/toolbox/keyedmutex"
)
type Cache struct {
updateLock keyedmutex.KeyedMutex
src func(string) (interface{}, error)
ttl time.Duration
maxSize int
// Lock protects cache, ll, and stats.
lock sync.Mutex
cache map[string]*list.Element
ll *list.List
stats Stats
}
type lruItem struct {
key string
createdAt time.Time
value interface{}
err error
}
type Config struct {
MaxSize int
TTL time.Duration // Zero to ignore.
Src func(string) (interface{}, error)
}
func New(conf Config) *Cache {
return &Cache{
updateLock: keyedmutex.New(),
src: conf.Src,
ttl: conf.TTL,
maxSize: conf.MaxSize,
2021-04-06 06:58:17 +00:00
lock: sync.Mutex{},
cache: make(map[string]*list.Element, conf.MaxSize+1),
2021-04-02 15:14:32 +00:00
ll: list.New(),
}
}
func (c *Cache) Get(key string) (interface{}, error) {
2021-04-06 15:51:16 +00:00
ok, val, err := c.get(key)
2021-04-06 06:58:17 +00:00
if ok {
return val, err
2021-04-02 15:14:32 +00:00
}
2021-04-06 06:58:17 +00:00
return c.load(key)
2021-04-02 15:14:32 +00:00
}
func (c *Cache) Evict(key string) {
c.lock.Lock()
defer c.lock.Unlock()
2021-04-06 06:58:17 +00:00
c.evict(key)
2021-04-02 15:14:32 +00:00
}
2021-04-06 06:58:17 +00:00
func (c *Cache) Stats() Stats {
2021-04-02 15:14:32 +00:00
c.lock.Lock()
defer c.lock.Unlock()
return c.stats
}