✨ It works!
This commit is contained in:
parent
40ed936c47
commit
3367cce0df
2 changed files with 73 additions and 9 deletions
42
ezcache.go
42
ezcache.go
|
|
@ -1,15 +1,17 @@
|
|||
package ezcache
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ezc[K comparable, V any] struct {
|
||||
fetch Fetcher[K, V]
|
||||
exp time.Duration
|
||||
cache map[K]V
|
||||
setTime map[K]time.Time
|
||||
fetch Fetcher[K, V]
|
||||
exp time.Duration
|
||||
cache map[K]V
|
||||
setTime map[K]time.Time
|
||||
lock sync.RWMutex
|
||||
timeLock sync.RWMutex
|
||||
}
|
||||
|
||||
func New[K comparable, V any](fetcher Fetcher[K, V], exp time.Duration) (Cache[K, V], error) {
|
||||
|
|
@ -28,11 +30,33 @@ func New[K comparable, V any](fetcher Fetcher[K, V], exp time.Duration) (Cache[K
|
|||
return c, nil
|
||||
}
|
||||
|
||||
var errUnimpl = errors.New("unimplemented")
|
||||
|
||||
func (c *ezc[K, V]) Get(key K) (V, error) {
|
||||
var val V
|
||||
return val, errUnimpl
|
||||
c.timeLock.RLock()
|
||||
setTime, ok := c.setTime[key]
|
||||
c.timeLock.RUnlock()
|
||||
if ok && time.Since(setTime) <= c.exp {
|
||||
c.lock.RLock()
|
||||
val, ok := c.cache[key]
|
||||
c.lock.RUnlock()
|
||||
if ok {
|
||||
return val, nil
|
||||
}
|
||||
}
|
||||
|
||||
val, err := c.fetch(key)
|
||||
if err != nil {
|
||||
return val, err
|
||||
}
|
||||
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
c.cache[key] = val
|
||||
|
||||
c.timeLock.Lock()
|
||||
defer c.timeLock.Unlock()
|
||||
c.setTime[key] = time.Now()
|
||||
|
||||
return val, nil
|
||||
}
|
||||
|
||||
func (c *ezc[K, V]) SetFetcher(f Fetcher[K, V]) error {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue