sm
/
cache
1
0
Fork 0

Added Get and reset method called GetR which resets the expiration

This commit is contained in:
Paul Montag 2016-07-14 23:00:01 -05:00
parent 1881a9bccb
commit d84a7fc928
2 changed files with 35 additions and 0 deletions

View File

@ -129,6 +129,29 @@ func (c *cache) Get(k string) (interface{}, bool) {
return item.Object, true
}
// get the item from cache and then reset the expiration date, this means
// you will need a full lock instead of a rlock
func (c *cache) GetR(k string, d time.Duration) (interface{}, bool) {
var e int64
if d > 0 {
e = time.Now().Add(d).UnixNano()
}
c.mu.Lock()
if item, found := c.get(k); found {
c.items[k] = Item{
Object: item,
Expiration: e,
}
c.mu.Unlock()
return item, found
}
c.mu.Unlock()
return nil, false
}
func (c *cache) get(k string) (interface{}, bool) {
item, found := c.items[k]
if !found {

View File

@ -76,6 +76,7 @@ func TestCacheTimes(t *testing.T) {
tc.Set("b", 2, NoExpiration)
tc.Set("c", 3, 20*time.Millisecond)
tc.Set("d", 4, 70*time.Millisecond)
tc.Set("e", 5, 100*time.Millisecond)
<-time.After(25 * time.Millisecond)
_, found = tc.Get("c")
@ -104,6 +105,17 @@ func TestCacheTimes(t *testing.T) {
if found {
t.Error("Found d when it should have been automatically deleted (later than the default)")
}
_, found = tc.GetR("e", 50 * time.Millisecond)
if !found {
t.Error("Should have found e because enough time hasn't passed")
}
<-time.After(35 * time.Millisecond)
_, found = tc.Get("e")
if !found {
t.Error("Should have still found e because it was reset")
}
}
func TestNewFrom(t *testing.T) {