redis 使用
大约 1 分钟
redis 使用
修改配置文件
修改 appsettings.json
配置文件
//redis服务配置
"RedisServer": {
"open": 1, //redis初始化开关(默认0)
"Cache": "127.0.0.1:6379,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=cache:",//用于缓存
"Session": "127.0.0.1:6379,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=session:"//用户登录会话管理
//...其他
}
使用
使用 RedisServer.Cache.Set("test", "hello");
注意引用:using ZR.Common.Cache
缓存监控
替换MonitorController
控制器中的GetCache
方法
/// <summary>
/// 获取缓存监控数据
/// </summary>
/// <returns></returns>
[HttpGet("monitor/cache")]
public IActionResult GetCache()
{
//已连接的客户端item1 当前redisIP,item2已连接的客户端列表
//(string, string)[] val = RedisServer.Cache.NodesServerManager.ClientList();
//获取当前数据库的key总量
(string, long)[] dbSize = RedisServer.Cache.NodesServerManager.DbSize();
//(string, string)[] names = RedisServer.Cache.NodesServerManager.ClientGetName();
(string, string)[] infos = RedisServer.Cache.NodesServerManager.Info();
(string, string)[] commandStats = RedisServer.Cache.NodesServerManager.Info(CSRedis.InfoSection.CommandStats);
var info = infos[0].Item2.Split("\r\n", StringSplitOptions.RemoveEmptyEntries);
var commandStat = commandStats[0].Item2.Split("\r\n", StringSplitOptions.RemoveEmptyEntries);
Dictionary<string, object> infoDic = new();
List<Dictionary<string, object>> commandStatDic = new();
foreach (var item in info)
{
var obj = item.Split(":", StringSplitOptions.RemoveEmptyEntries);
if (obj.Length > 1)
{
infoDic.Add(obj[0], obj[1]);
}
}
foreach (var item in commandStat)
{
var obj = item.Split(":", StringSplitOptions.RemoveEmptyEntries);
Dictionary<string, object> data = new();
if (obj.Length > 1)
{
data.Add("name", obj[0].Replace("cmdstat_", ""));
data.Add("value", SubstringBetween(obj[1], "calls=", ",usec="));
commandStatDic.Add(data);
}
}
return SUCCESS(new
{
dbSize = dbSize[0].Item2,
commandStats = commandStatDic,
info = infoDic
});
}
/// <summary>
/// 截取指定字符串中间内容
/// </summary>
/// <param name="sourse"></param>
/// <param name="startstr"></param>
/// <param name="endstr"></param>
/// <returns></returns>
public static string SubstringBetween(string sourse, string startstr, string endstr)
{
string result = string.Empty;
int startindex, endindex;
try
{
startindex = sourse.IndexOf(startstr);
if (startindex == -1)
return result;
string tmpstr = sourse.Substring(startindex + startstr.Length);
endindex = tmpstr.IndexOf(endstr);
if (endindex == -1)
return result;
result = tmpstr.Remove(endindex);
}
catch (Exception ex)
{
Console.WriteLine("MidStrEx Err:" + ex.Message);
}
return result;
}