fewer defers, document DeletePrefix

This commit is contained in:
Karl Seguin 2020-01-23 12:55:55 +08:00
parent 04261a5282
commit 79f9dcde21
2 changed files with 7 additions and 4 deletions

View file

@ -27,17 +27,17 @@ func (b *bucket) set(key string, value interface{}, duration time.Duration) (*It
expires := time.Now().Add(duration).UnixNano() expires := time.Now().Add(duration).UnixNano()
item := newItem(key, value, expires) item := newItem(key, value, expires)
b.Lock() b.Lock()
defer b.Unlock()
existing := b.lookup[key] existing := b.lookup[key]
b.lookup[key] = item b.lookup[key] = item
b.Unlock()
return item, existing return item, existing
} }
func (b *bucket) delete(key string) *Item { func (b *bucket) delete(key string) *Item {
b.Lock() b.Lock()
defer b.Unlock()
item := b.lookup[key] item := b.lookup[key]
delete(b.lookup, key) delete(b.lookup, key)
b.Unlock()
return item return item
} }
@ -73,15 +73,15 @@ func (b *bucket) deletePrefix(prefix string, deletables chan *Item) int {
} }
b.Lock() b.Lock()
defer b.Unlock()
for _, item := range items { for _, item := range items {
delete(lookup, item.key) delete(lookup, item.key)
} }
b.Unlock()
return len(items) return len(items)
} }
func (b *bucket) clear() { func (b *bucket) clear() {
b.Lock() b.Lock()
defer b.Unlock()
b.lookup = make(map[string]*Item) b.lookup = make(map[string]*Item)
b.Unlock()
} }

View file

@ -91,6 +91,9 @@ item, err := cache.Fetch("user:4", time.Minute * 10, func() (interface{}, error)
cache.Delete("user:4") cache.Delete("user:4")
``` ```
### DeletePrefix
`DeletePrefix` deletes all keys matching the provided prefix. Returns the number of keys removed.
### Clear ### Clear
`Clear` clears the cache. This method is **not** thread safe. It is meant to be used from tests. `Clear` clears the cache. This method is **not** thread safe. It is meant to be used from tests.