CachingFramework.Redis
CachingFramework.Redis copied to clipboard
Clear all keys + clear the entire database
I have a use case where I need to clear (invalidate) all the keys, Right now I'm using below code:
var tags = _cache.GetAllTags().ToArray();
await _cache.InvalidateKeysByTagAsync(tags);
but I also have some other items in Redis I need to remove, so I'm wondering it is would be good to add three new methods: InvalidateAllKeys InvalidateAllKeysAsync FlushAllDatabases
I have this implemented as a extension methods:
public static class ContextExtensions
{
/// <summary>
/// Removes all items in all databases
/// </summary>
public static void FlushAllDatabases(this IContext context)
{
var connectionMultiplexer = context.GetConnectionMultiplexer();
var endpoints = connectionMultiplexer.GetEndPoints(true);
foreach (var endpoint in endpoints)
{
var server = connectionMultiplexer.GetServer(endpoint);
server.FlushAllDatabases();
}
}
}
public static class CacheProviderExtensions
{
/// <summary>
/// Removes all the keys related to all tags.
/// </summary>
public static void InvalidateAll(this ICacheProvider cacheProvider)
{
var tags = cacheProvider.GetAllTags().ToArray();
cacheProvider.InvalidateKeysByTag(tags);
}
/// <summary>
/// Removes all the keys related to all tags.
/// </summary>
public static async Task InvalidateAllAsync(this ICacheProvider cacheProvider)
{
var tags = cacheProvider.GetAllTags().ToArray();
await cacheProvider.InvalidateKeysByTagAsync(tags);
}
}
maybe it is worth adding to the lib?
FlushAll is already provided:
https://github.com/thepirat000/CachingFramework.Redis/blob/e457548eafd6e2d4453ffadfe0790c96bcc24d54/src/CachingFramework.Redis/Providers/RedisCacheProvider.cs#L1913
@thepirat000 thank you for a quick reply, I didn't notice that one.
What about InvalidateAll interested in adding this?
I'm not sure, I think the name is not clear, it should probably be InvalidateAllTags since the keys not related to a tag will not be removed
I currently use this:
public static class CacheProviderExtensions
{
/// <summary>
/// Removes all the keys related to all tags.
/// </summary>
public static void InvalidateAllTags(this ICacheProvider cacheProvider)
{
var tags = cacheProvider.GetAllTags().ToArray();
cacheProvider.InvalidateKeysByTag(tags);
}
/// <summary>
/// Removes all the keys related to all tags.
/// </summary>
public static async Task InvalidateAllTagsAsync(this ICacheProvider cacheProvider)
{
var tags = cacheProvider.GetAllTags().ToArray();
await cacheProvider.InvalidateKeysByTagAsync(tags);
}
}
Can we add them or should they be left as extension methods?
I think this should be left as an extension method on your project. The purpose of the Tags is to invalidate a group of keys with a single server call. If you want to remove a group of tags, you should probably have another tag to group the other tag keys and so on...