Skip to content

Instantly share code, notes, and snippets.

@AndyButland
Created May 21, 2023 12:01
Show Gist options
  • Save AndyButland/e406eab7a8095ffa586fa3c5fbbb226a to your computer and use it in GitHub Desktop.
Save AndyButland/e406eab7a8095ffa586fa3c5fbbb226a to your computer and use it in GitHub Desktop.
public static class DistributedCacheExtensions
{
public static async Task RemoveWithPrefixAsync(this IDistributedCache cache, string keyPrefix)
{
if (cache is RedisCache redisCache)
{
ConnectionMultiplexer connection = await redisCache.GetConnectionAsync();
IDatabase db = connection.GetDatabase();
foreach (EndPoint? endpoint in connection.GetEndPoints())
{
IServer redisServer = connection.GetServer(endpoint);
List<RedisKey> keys = await redisServer
.KeysAsync(pattern: $"{keyPrefix}*")
.ToListAsync();
foreach (RedisKey key in keys)
{
await db.KeyDeleteAsync(key);
}
}
}
else
{
// If another IDistributedCache is registered, we skip the delete.
// In practice this will only be the "in-memory" implementation which will clear on restarts.
}
}
private static async Task<ConnectionMultiplexer> GetConnectionAsync(this RedisCache cache, CancellationToken cancellationToken = default)
{
#nullable disable
// Ensure connection is established
await (Task)typeof(RedisCache).InvokeMember("ConnectAsync", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, cache, new object[] { cancellationToken });
// Get connection multiplexer
FieldInfo fi = typeof(RedisCache).GetField("_connection", BindingFlags.Instance | BindingFlags.NonPublic);
return (ConnectionMultiplexer)fi.GetValue(cache);
#nullable disable
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment