Remove/Delete all/one item from StackExchange.Redis cache

Solution 1:

To remove a single item:

_cache.KeyDelete(key);

To remove all involves the FLUSHDB or FLUSHALL redis command; both are available in StackExchange.Redis; but, for reasons discussed here, they are not on the IDatabase API (because: they affect servers, not logical databases).

As per the "So how do I use them?" on that page:

server.FlushDatabase(); // to wipe a single database, 0 by default
server.FlushAllDatabases(); // to wipe all databases

(quite possibly after using GetEndpoints() on the multiplexer)

Solution 2:

I could not able to flush database in Azure Redis Cache, got this error:

This operation is not available unless admin mode is enabled: FLUSHDB

Instead iterate through all keys to delete:

var endpoints = connectionMultiplexer.GetEndPoints();
var server = connectionMultiplexer.GetServer(endpoints.First());
//FlushDatabase didn't work for me: got error admin mode not enabled error
//server.FlushDatabase();
var keys = server.Keys();
foreach (var key in keys)
{
  Console.WriteLine("Removing Key {0} from cache", key.ToString());
  _cache.KeyDelete(key);
}

Solution 3:

Both answers by @Rasi and @Marc Gravell contain pieces of code needed. Based on above, here is working snippet assuming there is just 1 server:

You need to connect to redis with allowAdmin=true, one way to obtain such options is to assign AllowAdmin to already parsed string:

var options = ConfigurationOptions.Parse("server:6379");
options.AllowAdmin = true;
var redis = ConnectionMultiplexer.Connect(options);

Then to flush all databases:

var endpoints = redis.GetEndPoints();
var server = redis.GetServer(endpoints[0]);
server.FlushAllDatabases();

Above will work on any redis deployment, not just Azure.

Solution 4:

You can delete hash as well ie if you want to clear specific value from any cached list. For example, we have an emp list and inside with different department as cached.

public static void DeleteHash(string key, string cacheSubKey)
        {
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key");

            Cache.HashDelete(key, cacheSubKey);
        }

so you can pass Key name and cache subkey as well.