Add functionality allowing to get expired value (stale) from cache
This commit is contained in:
parent
7ac151875f
commit
8f028ba51c
19
cache.go
19
cache.go
|
@ -135,6 +135,25 @@ func (c *cache) Get(k string) (interface{}, bool) {
|
||||||
return item.Object, true
|
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.
|
// 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
|
// 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
|
// never expires a zero value for time.Time is returned), and a bool indicating
|
||||||
|
|
|
@ -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) {
|
func TestSerializeUnserializable(t *testing.T) {
|
||||||
tc := New(DefaultExpiration, 0)
|
tc := New(DefaultExpiration, 0)
|
||||||
ch := make(chan bool, 1)
|
ch := make(chan bool, 1)
|
||||||
|
|
Loading…
Reference in New Issue