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

前端 未结 4 523
执念已碎
执念已碎 2021-01-31 14:54

I am using StackExchange.Redis client with Azure Redis Cache Service. Here is my class,

public class RedisCacheService : ICacheService
{
    private readonly ISe         


        
相关标签:
4条回答
  • 2021-01-31 15:05

    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.

    0 讨论(0)
  • 2021-01-31 15:15

    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.

    0 讨论(0)
  • 2021-01-31 15:17

    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);
    }
    
    0 讨论(0)
  • 2021-01-31 15:27

    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)

    0 讨论(0)
提交回复
热议问题