我正在使用StackExchange.Redis使用多个数据库在redis缓存中存储和检索项目。
但是,我无法弄清楚如何在所有数据库中检索键/值。 以下代码从默认数据库0中检索密钥,我找不到如何更改它以从每个数据库中检索密钥
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;
}
有什么建议吗?
答案 0 :(得分:3)
似乎我找到了答案 - 需要将数据库名称传递给实际的.Keys,如下所示
var keys = server.Keys(_dataCache.Database);
答案 1 :(得分:1)
您需要编写:var keys = server.Keys( int dbName ); 我在示例中添加了如何通过键获取值
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);
}
答案 2 :(得分:0)
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
try
{
string folderPath = @"C:\RedisCache\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + @"\";
Directory.CreateDirectory(folderPath);
IDictionary<string, string> dicts = GetDataFromDataBase();
using (TextWriter tw = new StreamWriter(folderPath + "BatchFile.bat"))
{
foreach (var dic in dicts)
{
tw.WriteLine("REDIS COMMAND");
}
}
}
catch(Exception ex)
{
throw ex;
}
}
public static ConnectionMultiplexer Connection
{
get
{
return ConnectionMultiplexer.Connect("serverName: port");
}
}
public static Dictionary<string, string> GetDataFromDataBase(string 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 static string GetFromDB(int dbName, string key)
{
var db = Connection.GetDatabase(dbName);
return db.StringGet(key);
}
}
}