diff --git a/README.md b/README.md index 4a8efa1..fd62366 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,7 @@ cache.StartJanitor() | GetKeysByPattern | Retrieves a slice of keys that matches a given pattern. | | Delete | Removes a key from the cache. | | DeleteAll | Removes multiple keys from the cache. | +| DeleteKeysByPattern | Removes all keys that that matches a given pattern. | | Count | Gets the size of the cache. This includes cache keys which may have already expired, but have not been removed yet. | | Clear | Wipes the cache. | | TTL | Gets the time until a cache key expires. | diff --git a/gocache.go b/gocache.go index 4a22b4e..ab462db 100644 --- a/gocache.go +++ b/gocache.go @@ -388,8 +388,7 @@ func (cache *Cache) GetAll() map[string]interface{} { // cache.GetKeysByPattern("*some*", 0) will return all keys containing "some" in them // cache.GetKeysByPattern("*some*", 5) will return 5 keys (or less) containing "some" in them // -// Note that GetKeysByPattern does not trigger active evictions, nor does it count as accessing the entry, the latter -// only applying if the cache uses the LeastRecentlyUsed eviction policy. +// Note that GetKeysByPattern does not trigger active evictions, nor does it count as accessing the entry (if LRU). // The reason for that behavior is that these two (active eviction and access) only applies when you access the value // of the cache entry, and this function only returns the keys. func (cache *Cache) GetKeysByPattern(pattern string, limit int) []string { @@ -435,6 +434,13 @@ func (cache *Cache) DeleteAll(keys []string) int { return numberOfKeysDeleted } +// DeleteKeysByPattern deletes all entries matching a given key pattern and returns the number of entries deleted. +// +// Note that DeleteKeysByPattern does not trigger active evictions, nor does it count as accessing the entry (if LRU). +func (cache *Cache) DeleteKeysByPattern(pattern string) int { + return cache.DeleteAll(cache.GetKeysByPattern(pattern, 0)) +} + // Count returns the total amount of entries in the cache, regardless of whether they're expired or not func (cache *Cache) Count() int { cache.mutex.RLock() diff --git a/gocache_test.go b/gocache_test.go index 4241ff4..2201423 100644 --- a/gocache_test.go +++ b/gocache_test.go @@ -777,6 +777,23 @@ func TestCache_DeleteAll(t *testing.T) { } } +func TestCache_DeleteKeysByPattern(t *testing.T) { + cache := NewCache() + cache.Set("a1", []byte("v")) + cache.Set("a2", []byte("v")) + cache.Set("b1", []byte("v")) + if len(cache.GetByKeys([]string{"a1", "a2", "b1"})) != 3 { + t.Error("Expected keys 1, 2 and 3 to exist") + } + numberOfDeletedKeys := cache.DeleteKeysByPattern("a*") + if numberOfDeletedKeys != 2 { + t.Errorf("Expected 2 keys to have been deleted, but only %d were deleted", numberOfDeletedKeys) + } + if _, exists := cache.Get("b1"); !exists { + t.Error("Expected key b1 to still exist") + } +} + func TestCache_TTL(t *testing.T) { cache := NewCache() ttl, err := cache.TTL("key")