Add functionality allowing to get expired value (stale) from cache

This commit is contained in:
oskarwojciski 2017-07-12 08:51:14 +02:00
parent 7ac151875f
commit 8f028ba51c
No known key found for this signature in database
GPG Key ID: D8CA6798EEF6DCA8
2 changed files with 51 additions and 0 deletions

View File

@ -135,6 +135,25 @@ func (c *cache) Get(k string) (interface{}, bool) {
return item.Object, true
}
// Get full Item from cache (with info about expiration).
// Returns full Item, when allowExpired is set to true returning item even if already expired and a bool indicating
// whether the key was found.
func (c *cache) GetItem(k string, allowExpired bool) (Item, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
item, found := c.items[k]
if !found {
return Item{}, false
}
if !allowExpired && item.Expired() {
return Item{}, false
}
return item, true
}
// GetWithExpiration returns an item and its expiration time from the cache.
// It returns the item or nil, the expiration time if one is set (if the item
// never expires a zero value for time.Time is returned), and a bool indicating

View File

@ -1413,6 +1413,38 @@ func TestFileSerialization(t *testing.T) {
}
}
func TestGetItem(t *testing.T) {
tc := New(DefaultExpiration, 0)
tc.Set("int8", int8(5), 25*time.Microsecond)
n, err := tc.DecrementInt8("int8", 2)
if err != nil {
t.Error("Error decrementing:", err)
}
if n != 3 {
t.Error("Returned number is not 3:", n)
}
time.Sleep(50 * time.Microsecond)
x, found := tc.Get("int8")
if found {
t.Error("int8 should be expired")
}
_, found = tc.GetItem("int8", false)
if found {
t.Error("int8 should be expired")
}
item, found := tc.GetItem("int8", true)
if !found {
t.Error("int8 stale was not found")
}
if item.Object.(int8) != 3 {
t.Error("int8 is not 3:", x)
}
}
func TestSerializeUnserializable(t *testing.T) {
tc := New(DefaultExpiration, 0)
ch := make(chan bool, 1)