feat: public extend

Signed-off-by: rfyiamcool <rfyiamcool@163.com>
This commit is contained in:
rfyiamcool
2023-10-22 22:14:28 +08:00
parent 62cd8cc8c3
commit 2977b36b74
3 changed files with 47 additions and 0 deletions

View File

@@ -163,6 +163,17 @@ func (c *Cache[T]) Replace(key string, value T) bool {
return true
}
// Extend change the expiry of the item by the specified duration relative to the current time.
func (c *Cache[T]) Extend(key string, duration time.Duration) bool {
item := c.bucket(key).get(key)
if item == nil {
return false
}
item.Extend(duration)
return true
}
// Attempts to get the value from the cache and calles fetch on a miss (missing
// or stale item). If fetch returns an error, no value is cached and the error
// is returned back to the caller.

View File

@@ -33,6 +33,31 @@ func Test_Setnx(t *testing.T) {
assert.Equal(t, cache.ItemCount(), 1)
}
func Test_Extend(t *testing.T) {
cache := New(Configure[string]())
defer cache.Stop()
assert.Equal(t, cache.ItemCount(), 0)
// non exist
ok := cache.Extend("spice", time.Minute*10)
assert.Equal(t, false, ok)
// exist
cache.Set("spice", "flow", time.Minute)
assert.Equal(t, cache.ItemCount(), 1)
ok = cache.Extend("spice", time.Minute*10) // 10 + 10
assert.Equal(t, true, ok)
item := cache.Get("spice")
less := time.Minute*22 < time.Duration(item.expires)
assert.Equal(t, true, less)
more := time.Minute*18 < time.Duration(item.expires)
assert.Equal(t, true, more)
assert.Equal(t, cache.ItemCount(), 1)
}
func Test_CacheDeletesAValue(t *testing.T) {
cache := New(Configure[string]())
defer cache.Stop()

View File

@@ -111,8 +111,19 @@ cache.Delete("user:4")
`Clear` clears the cache. If the cache's gc is running, `Clear` waits for it to finish.
### Extend
The life of an item can be changed via the `Extend` method. This will change the expiry of the item by the specified duration relative to the current time.
```go
cache.Extend("user:4", time.Minute * 10)
// or
item := cache.Get("user:4")
if item != nil {
item.Extend(time.Minute * 10)
}
```
### Replace
The value of an item can be updated to a new value without renewing the item's TTL or it's position in the LRU: