Get all key and values from all redis databases?
12,365
Solution 1
it seems I found the answers - need to pass the database name to the actual .Keys, as below
var keys = server.Keys(_dataCache.Database);
Solution 2
You need to write: var keys = server.Keys(int dbName); I added in the example how to get the values by key
public static ConnectionMultiplexer Connection
{
get
{
return ConnectionMultiplexer.Connect("serverName: port");
}
}
public Dictionary<string, string> GetDataFromDataBase(srting sPattern = "*")
{
int dbName = 2; //or 0, 1, 2
Dictionary<string, string> dicKeyValue = new Dictionary<string, string>();
var keys = Connection.GetServer("serverName: port").Keys(dbName, pattern: sPattern);
string[] keysArr = keys.Select(key =>(string)key).ToArray();
foreach(var key in keysArr)
{
dicKeyValue.Add(key, GetFromDB(dbName , key));
}
return dicKeyValue;
}
public string GetFromDB(int dbName, string key)
{
var db = Connection.GetDatabase(dbName);
return db.StringGet(key);
}
Related videos on Youtube
Comments
-
trek almost 2 years
I'm using StackExchange.Redis to store and retrieve items in redis cache using multiple databases.
However, I cannot figure out how to retrieve key/values across ALL databases. The following code retrieves keys from the default database 0, and I cannot find how to change it to retrieve keys from each database
public IEnumerable<KeyValuePair<string, object>> GetAll() { var result = new List<KeyValuePair<string, object>>(); var endpoints = _dataCache.Multiplexer.GetEndPoints(); var server = _dataCache.Multiplexer.GetServer(endpoints.First()); var keys = server.Keys(); foreach (var key in keys) { Console.WriteLine(key.ToString()); } return result; }
Any suggestions?
-
Chris Tanner over 7 yearsProbably not a good idea in production, check out the SCAN command instead.
-
Arkhangelskiy Evgeniy over 7 yearswhich command to be used (KEYS or SCAN) will be decided by server based on server capabilities.
-
Jay Shah almost 6 yearsAnd how do I get values from keys variable ?