Search code examples
c#cachingstackexchange.redis

Get all keys from Redis Cache database


I am using Redis cache for caching purpose (specifically stackexchange.Redis C# driver. Was wondering is there any ways to get all the keys available in cache at any point in time. I mean the similar thing I can do in ASP.NET cache object (below code sample)

var keys = Cache.GetEnumerator();                               
while(keys.MoveNext())
{
     keys.Key.ToString() // Key
}

Redis documentation talks about KESY command but do stackexchange.Redis have implementation for that command.

Debugging through the connection.GetDataBase() instance, I don't see any method / property for that.

Any idea?


Solution

  • Function that you need is under IServer interface, and can be reached with:

    ConnectionMultiplexer m = CreateConnection();
    m.GetServer("host").Keys();
    

    Note that prior to version 2.8 of redis server that will use KEYS command you mentioned, and it can be very slow in certain cases. However if you use redis 2.8+ - it will use SCAN command instead, which performs better. Also ensure that you really need to get all keys, in my practice I've never ever needed this.