Listing and removing all cache entries from a given group using IDistributedCache
Asked Answered
S

2

7

I'm storing some key generated by users in a IDistributedCache set up.

The key are long lived and they can be manually revoked by an user, if the user knows each one of them:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDistributedMemoryCache();
    //...
}

//ControllerBase:

//Adding the key:
await _cache.SetAsync(userKey, userId, new DistributedCacheEntryOptions 
{ 
    AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(10)
});

//Removing the key:
await _cache.RemoveAsync(key);

Now, what I want to do is to be able to list all keys still present in the cache that were created by one of the users. Also, I want to be able to bulk delete them.

Is there such a functionality available right now? Maybe with cancelation tokens? How can I do that?

Spheroidicity answered 9/4, 2019 at 19:3 Comment(0)
S
11

No, you can only work with one key at a time with IDistributedCache. Mass key eviction and similar scenarios are beyond the scope of this facade. If you need to handle more advanced scenarios, then you should connect to your cache directly, using the appropriate client. For example, for a Redis backing, you can use the StackExchange.Redis package, and issue whatever commands you like via that.

Sidewalk answered 9/4, 2019 at 19:20 Comment(0)
D
1

You can flush the store using FLUSHALL method(IServer.FlushAllDatabasesAsync() - please note that AllowAdmin flag must be true in the config). The method exist in IServer interface which can be retrieved from IConnectionMultiplexer. If you're using StackExchange.Redis DI, IDistributedCache doesn't have the ability to do so as of now. You can use System.Reflection to get IConnectionMultiplexer from (RedisCache)IDistributedCache.

Deserted answered 28/6, 2022 at 20:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.