mh_frame_sps/APT.Infrastructure.Api/Redis/CsRedisManager.cs

510 lines
16 KiB
C#
Raw Normal View History

2026-04-07 13:47:52 +08:00
using APT.Infrastructure.Core;
using CSRedis;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace APT.Infrastructure.Api.Redis
{
public class CsRedisManager
{
static CSRedisClient redisManger = null;
public static CSRedisClient GetClient()
{
return redisManger;
}
static JsonSerializerSettings _jsonSetting;
public static string ConvertJson<T>(T value)
{
string result = value is string ? value.ToString() : JsonConvert.SerializeObject(value, _jsonSetting);
return result;
}
static CsRedisManager()
{
_jsonSetting = new JsonSerializerSettings();
_jsonSetting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
RedisOption option = ConfigurationManager.RedisOption;
if (option != null)
{
//SysCustomKey = option.RedisPrefixKey;
//RedisConnectionString = option.RedisConnectionString;
//RedisPwd = option.RedisConnectionPwd;
}
else
{
throw new Exception($"未加载redis.json文件");
}
redisManger = new CSRedisClient(option.RedisConnectionString); //Redis的连接字符串
}
/// <summary>
/// TradeManageMessage 和 TradeManageMessage:MQ队列
/// </summary>
/// <returns></returns>
public static bool EnQeenTradeManageMessage(string value)
{
try
{
LoggerManager.GetLogger("redis").Info("yinzhou--EnQeenTradeManageMessage:" + value);
//从头部插入
GetClient().LPush("TradeManageMessage", value);
GetClient().LPush("TradeManageMessage:MQ", value);
return true;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"EnQeenTradeManageMessage:key=TradeManageMessage:MQ,value={value},错误信息:{e}");
return false;
}
}
/// <summary>
/// TradeManageMessage 和 TradeManageMessage:MQ队列
/// </summary>
/// <returns></returns>
public static bool EnQeenTradeManageMessage<T>(T value)
{
try
{
//从头部插入
GetClient().LPush("TradeManageMessage", value);
GetClient().LPush("TradeManageMessage:MQ", value);
return true;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"EnQeenTradeManageMessage:key=TradeManageMessage:MQ,value={value},错误信息:{e}");
return false;
}
}
public static bool EnQueen(string key, string value)
{
try
{
//从头部插入
GetClient().LPush(key, value);
return true;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"EnQueen:key={key},value={value},错误信息:{e}");
return false;
}
}
public static string DeQueen(string key)
{
string result = "";
try
{
//从尾部取值
result = GetClient().RPop(key);
return result;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"DeQueen:key={key},错误信息:{e}");
return result;
}
}
//redis订阅模式
public static void Sub(string key, Action<string> action)
{
GetClient().Subscribe((key, msg => action(msg.Body)));
}
public static string[] DeQueenAll(string key)
{
string[] result = { };
try
{
long len = GetClient().LLen(key);
//取出指定数量数据
result = GetClient().LRange(key, 0, len - 1);
//删除指定数据
bool res = GetClient().LTrim(key, len, -1);
return result;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"DeQueen:key={key},错误信息:{e}");
return result;
}
}
public static bool EnQueen<T>(string key, T value)
{
try
{
//从头部插入
long len = GetClient().LPush(key, value);
if (len > 0)
return true;
else
return false;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"EnQueenObj:key={key},value={value},错误信息:{e}");
return false;
}
}
public static T DeQueen<T>(string key)
{
T result = default(T);
try
{
//从尾部取值
result = GetClient().RPop<T>(key);
return result;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"DeQueen:key={key},错误信息:{e}");
return result;
}
}
/// <summary>
/// 设置hash值
/// </summary>
/// <param name="key"></param>
/// <param name="field"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool SetHash(string key, string field, string value)
{
try
{
GetClient().HSet(key, field, value);
return true;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"SetHash:key={key},value={value},错误信息:{e}");
return false;
}
}
/// <summary>
/// 根据表名键名获取hash值
/// </summary>
/// <param name="key">表名</param>
/// <param name="field">键名</param>
/// <returns></returns>
public static string GetHash(string key, string field)
{
string result = "";
try
{
result = GetClient().HGet(key, field);
return result;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"GetHash:key={key},错误信息:{e}");
return result;
}
}
/// <summary>
/// 获取指定key中所有字段
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static Dictionary<string, string> GetHashAll(string key)
{
try
{
var result = GetClient().HGetAll(key);
return result;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"GetHash:key={key},错误信息:{e}");
return new Dictionary<string, string>();
}
}
/// <summary>
/// 根据表名键名删除hash值
/// </summary>
/// <param name="key">表名</param>
/// <param name="field">键名</param>
/// <returns></returns>
public static long DeleteHash(string key, string field)
{
long result = 0;
try
{
result = GetClient().HDel(key, field);
return result;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"GetHash:key={key}", e);
throw new Exception($"redis error:DeleteHash: key ={ key },错误信息:{e}");
}
}
// <summary>
/// 保存单个key value
/// </summary>
/// <param name="key">Redis Key</param>
/// <param name="value">保存的值</param>
/// <param name="expiry">过期时间</param>
/// <returns></returns>
public static async Task<bool> StringSetAsync<T>(string key, T value, int expiry = -1)
{
try
{
string json = ConvertJson(value);
var result = await GetClient().SetAsync(key, json, expiry);
return result;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"StringSetAsync:key={key}", e);
throw new Exception($"redis error:StringSetAsync: key ={ key },错误信息:{e}");
}
}
/// <summary>
/// 保存一个对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="obj"></param>
/// <param name="expiry"></param>
/// <returns></returns>
public static bool StringSet<T>(string key, T obj, int expiry = -1)
{
try
{
string json = ConvertJson(obj);
var result = GetClient().Set(key, json, expiry);
return result;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"StringSet:key={key},错误信息:{e}");
throw new Exception($"redis error:StringSet: key ={ key },错误信息:{e}");
}
}
/// <summary>
/// 获取单个key的值
/// </summary>
/// <param name="key">Redis Key</param>
/// <returns></returns>
public static async Task<string> StringGetAsync(string key)
{
try
{
var result = await GetClient().GetAsync(key);
return result;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"StringGetAsync:key={key},错误信息:{e}");
throw new Exception($"redis error:StringGetAsync: key ={ key },错误信息:{e}");
}
}
public static string StringGet(string key)
{
try
{
var result = GetClient().Get(key);
return result;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"StringGet:key={key},错误信息:{e}");
throw new Exception($"redis error:StringGet: key ={ key },错误信息:{e}");
}
}
public static async Task<T> StringGetAsync<T>(string key)
{
try
{
var result = await GetClient().GetAsync<T>(key);
return result;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"StringGetAsync:key={key},错误信息:{e}");
throw new Exception($"redis error:StringGetAsync: key ={ key },错误信息:{e}");
}
}
public static T StringGet<T>(string key)
{
try
{
var result = GetClient().Get<T>(key);
return result;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"StringGet:key={key},错误信息:{e}");
throw new Exception($"redis error:StringGet: key ={ key },错误信息:{e}");
}
}
/// <summary>
/// 删除单个key
/// </summary>
/// <param name="key">redis key</param>
/// <returns>是否删除成功</returns>
public static bool KeyDelete(string key)
{
try
{
var result = GetClient().Del(key);
return true;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"StringGet:key={key},错误信息:{e}");
throw new Exception($"redis error:KeyDelete: key ={ key },错误信息:{e}");
}
}
public static async Task<bool> KeyDeleteAsync(string key)
{
try
{
var result = await GetClient().DelAsync(key);
return true;
}
catch (Exception e)
{
LoggerManager.GetLogger("redis").Error($"StringGet:key={key},错误信息:{e}");
throw new Exception($"redis error:KeyDeleteAsync: key ={ key },错误信息:{e}");
}
}
/// <summary>
/// 判断key是否存储
/// </summary>
/// <param name="key">redis key</param>
/// <returns></returns>
public static bool KeyExists(string key)
{
return GetClient().Exists(key);
}
public static async Task<bool> KeyExistsAsync(string key)
{
return await GetClient().ExistsAsync(key);
}
/// <summary>
/// 获取list的redis
/// </summary>
/// <param name="orgid"></param>
/// <returns></returns>
public static Dictionary<string, string> GetListKeys(Guid orgid)
{
return GetClient().HGetAll("opt_list_" + orgid);
}
/// <summary>
/// 删除list中的某张表数据
/// </summary>
/// <param name="orgid"></param>
/// <param name="name"></param>
/// <returns></returns>
public static bool DeleteListKeys(Guid orgid, string name)
{
if (GetClient().HExists("opt_list_" + orgid, name))
{
GetClient().HDel("opt_list_" + orgid, name);
}
return true;
}
/// <summary>
/// 是否存在
/// </summary>
/// <param name="orgid"></param>
/// <param name="name"></param>
/// <returns></returns>
public static bool ExistsListKeys(Guid orgid, string name)
{
return GetClient().HExists("opt_list_" + orgid, name);
}
/// <summary>
/// 获取list中表的rediskey
/// </summary>
/// <param name="orgid"></param>
/// <param name="name"></param>
/// <returns></returns>
public static string GetListKey(Guid orgid, string name)
{
return GetClient().HGet("opt_list_" + orgid, name);
}
//private object deleteCache( Method method, Object[] args)
//{
// object flag = false;
// String fieldkey = parseKey(method, args);
// try
// {
// if (fieldkey.equals(""))
// {
// cacheClient.del(cache.key());
// }
// else
// {
// cacheClient.hdel(cache.key(), fieldkey);
// }
// flag = true;
// }
// catch (Exception e)
// {
// //System.out.println(e.getMessage());
// flag = false;
// }
// return flag;
//}
/**
* field
* @param key
* @param method
* @param args
* @return
* @throws Exception
*/
// public string parseKey(Method method, Object[] args)
// {
// string fieldKey = "";
// for (int i = 0; i < method.getParameters().length; i++)
// {
// Parameter p = method.getParameters()[i];
// FieldAnnotation f = p.getAnnotation(FieldAnnotation.class);
// if(f!=null) {
// fieldKey+=args[i].toString()+":";
// }else {
// FieldOnlyKeyAnnotation fo = p.getAnnotation(FieldOnlyKeyAnnotation.class);
// if(fo != null) {
// fieldKey+=args[i].toString();
//}
// }
// }
// return fieldKey;
// }
}
}