Invalidate cache based on Memo's cache duration
This commit is contained in:
+16
-3
@@ -2,6 +2,7 @@ package memo
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type (
|
type (
|
||||||
@@ -9,6 +10,9 @@ type (
|
|||||||
f Func
|
f Func
|
||||||
mu sync.Mutex //guards cache
|
mu sync.Mutex //guards cache
|
||||||
cache *entry
|
cache *entry
|
||||||
|
|
||||||
|
cacheDur time.Duration
|
||||||
|
lastCache time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
Func func() (interface{}, error)
|
Func func() (interface{}, error)
|
||||||
@@ -26,16 +30,25 @@ type (
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
func New(f Func) *Memo {
|
func New(f Func, cd time.Duration) *Memo {
|
||||||
return &Memo{
|
return &Memo{
|
||||||
f: f,
|
f: f,
|
||||||
|
cacheDur: cd,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (memo *Memo) Invalidate() {
|
// Invalidate resets the cache to nil if the memo's given cache duration has
|
||||||
|
// elapsed, and returns true if the cache was actually invalidated.
|
||||||
|
func (memo *Memo) Invalidate() bool {
|
||||||
|
defer memo.mu.Unlock()
|
||||||
memo.mu.Lock()
|
memo.mu.Lock()
|
||||||
|
|
||||||
|
if memo.cache != nil && time.Now().Sub(memo.lastCache) > memo.cacheDur {
|
||||||
memo.cache = nil
|
memo.cache = nil
|
||||||
memo.mu.Unlock()
|
memo.lastCache = time.Now()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (memo *Memo) Get() (value interface{}, err error) {
|
func (memo *Memo) Get() (value interface{}, err error) {
|
||||||
|
|||||||
Reference in New Issue
Block a user