C#Redis缓存帮助类

网友投稿 849 2022-10-06

C#Redis缓存帮助类

C#Redis缓存帮助类

工厂创建类:

public class CacheFactory { private static ICache cache = null; private static readonly object lockHelper = new object(); public static ICache Cache { get { if (cache == null) { lock (lockHelper) { if (cache == null) { switch (CacheProvider) { case "Redis":cache = new RedisCacheImp(); break; default: case "Memory":cache = new MemoryCacheImp();break; } } } } return cache; } } public static string CacheProvider { get; set; } = "Redis"; }

接口:

public interface ICache { bool SetCache(string key, T value, DateTime? expireTime = null); T GetCache(string key); bool RemoveCache(string key); #region Hash int SetHashFieldCache(string key, string fieldKey, T fieldValue); int SetHashFieldCache(string key, Dictionary dict); T GetHashFieldCache(string key, string fieldKey); Dictionary GetHashFieldCache(string key, Dictionary dict); Dictionary GetHashCache(string key); List GetHashToListCache(string key); bool RemoveHashFieldCache(string key, string fieldKey); Dictionary RemoveHashFieldCache(string key, Dictionary dict); #endregion }

RedisCacheImp

public class RedisCacheImp : ICache { private IDatabase cache; private ConnectionMultiplexer connection; public RedisCacheImp() { connection = ConnectionMultiplexer.Connect(RedisConnectionString); cache = connection.GetDatabase(); } public bool SetCache(string key, T value, DateTime? expireTime = null) { try { var jsonOption = new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; string strValue = JsonConvert.SerializeObject(value, jsonOption); if (string.IsNullOrEmpty(strValue)) return false; if (expireTime == null) return cache.StringSet(key, strValue); else return cache.StringSet(key, strValue, (expireTime.Value - DateTime.Now)); } catch (Exception ex) { LogHelper.Error(ex); } return false; } public bool RemoveCache(string key) { return cache.KeyDelete(key); } public T GetCache(string key) { var t = default(T); try { var value = cache.StringGet(key); if (string.IsNullOrEmpty(value)) { return t; } t = JsonConvert.DeserializeObject(value); } catch (Exception ex) { LogHelper.Error(ex); } return t; } #region Hash public int SetHashFieldCache(string key, string fieldKey, T fieldValue) { return SetHashFieldCache(key, new Dictionary { { fieldKey, fieldValue } }); } public int SetHashFieldCache(string key, Dictionary dict) { int count = 0; var jsonOption = new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; foreach (string fieldKey in dict.Keys) { string fieldValue = JsonConvert.SerializeObject(dict[fieldKey], jsonOption); count += cache.HashSet(key, fieldKey, fieldValue) ? 1 : 0; } return count; } public T GetHashFieldCache(string key, string fieldKey) { var dict = GetHashFieldCache(key, new Dictionary { { fieldKey, default(T) } }); return dict[fieldKey]; } public Dictionary GetHashFieldCache(string key, Dictionary dict) { foreach (string fieldKey in dict.Keys) { string fieldValue = cache.HashGet(key, fieldKey); dict[fieldKey] = JsonConvert.DeserializeObject(fieldValue); } return dict; } public Dictionary GetHashCache(string key) { Dictionary dict = new Dictionary(); var hashFields = cache.HashGetAll(key); foreach (HashEntry field in hashFields) { dict[field.Name] = JsonConvert.DeserializeObject(field.Value); } return dict; } public List GetHashToListCache(string key) { List list = new List(); var hashFields = cache.HashGetAll(key); foreach (HashEntry field in hashFields) { list.Add(JsonConvert.DeserializeObject(field.Value)); } return list; } public bool RemoveHashFieldCache(string key, string fieldKey) { Dictionary dict = new Dictionary { { fieldKey, false } }; dict = RemoveHashFieldCache(key, dict); return dict[fieldKey]; } public Dictionary RemoveHashFieldCache(string key, Dictionary dict) { foreach (string fieldKey in dict.Keys) { dict[fieldKey] = cache.HashDelete(key, fieldKey); } return dict; } #endregion public void Dispose() { if (connection != null) { connection.Close(); } GC.SuppressFinalize(this); } public string RedisConnectionString { get; set; } }

MemoryCacheImp

public class MemoryCacheImp : ICache { public static IServiceProvider ServiceProvider { get; set; } private IMemoryCache cache = ServiceProvider.GetService(); public bool SetCache(string key, T value, DateTime? expireTime = null) { try { if (expireTime == null) return cache.Set(key, value) != null; return cache.Set(key, value, (expireTime.Value - DateTime.Now)) != null; } catch (Exception ex) { LogHelper.Error(ex); } return false; } public bool RemoveCache(string key) { cache.Remove(key); return true; } public T GetCache(string key) { var value = cache.Get(key); return value; } #region Hash public int SetHashFieldCache(string key, string fieldKey, T fieldValue) { return SetHashFieldCache(key, new Dictionary { { fieldKey, fieldValue } }); } public int SetHashFieldCache(string key, Dictionary dict) { int count = 0; foreach (string fieldKey in dict.Keys) { count += cache.Set(key, dict) != null ? 1 : 0; } return count; } public T GetHashFieldCache(string key, string fieldKey) { var dict = GetHashFieldCache(key, new Dictionary { { fieldKey, default(T) } }); return dict[fieldKey]; } public Dictionary GetHashFieldCache(string key, Dictionary dict) { var hashFields = cache.Get>(key); foreach (KeyValuePair keyValuePair in hashFields.Where(p => dict.Keys.Contains(p.Key))) { dict[keyValuePair.Key] = keyValuePair.Value; } return dict; } public Dictionary GetHashCache(string key) { Dictionary dict = new Dictionary(); var hashFields = cache.Get>(key); foreach (string field in hashFields.Keys) { dict[field] = hashFields[field]; } return dict; } public List GetHashToListCache(string key) { List list = new List(); var hashFields = cache.Get>(key); foreach (string field in hashFields.Keys) { list.Add(hashFields[field]); } return list; } public bool RemoveHashFieldCache(string key, string fieldKey) { Dictionary dict = new Dictionary { { fieldKey, false } }; dict = RemoveHashFieldCache(key, dict); return dict[fieldKey]; } public Dictionary RemoveHashFieldCache(string key, Dictionary dict) { var hashFields = cache.Get>(key); foreach (string fieldKey in dict.Keys) { dict[fieldKey] = hashFields.Remove(fieldKey); } return dict; } #endregion }

日志记录:

public class LogHelper { private static readonly Logger log = LogManager.GetLogger(string.Empty); public static void Trace(object msg, Exception ex = null) { if (ex == null) { log.Trace(msg.ParseToString()); } else { log.Trace(msg + GetExceptionMessage(ex)); } } public static void Debug(object msg, Exception ex = null) { if (ex == null) { log.Debug(msg.ParseToString()); } else { log.Debug(msg + GetExceptionMessage(ex)); } } public static void Info(object msg, Exception ex = null) { if (ex == null) { log.Info(msg.ParseToString()); } else { log.Info(msg + GetExceptionMessage(ex)); } } public static void Warn(object msg, Exception ex = null) { if (ex == null) { log.Warn(msg.ParseToString()); } else { log.Warn(msg + GetExceptionMessage(ex)); } } public static void Error(object msg, Exception ex = null) { if (ex == null) { log.Error(msg.ParseToString()); } else { log.Error(msg + GetExceptionMessage(ex)); } } public static void Error(Exception ex) { if (ex != null) { log.Error(GetExceptionMessage(ex)); } } public static void Fatal(object msg, Exception ex = null) { if (ex == null) { log.Fatal(msg.ParseToString()); } else { log.Fatal(msg + GetExceptionMessage(ex)); } } public static void Fatal(Exception ex) { if (ex != null) { log.Fatal(GetExceptionMessage(ex)); } } private static string GetExceptionMessage(Exception ex) { string message = string.Empty; if (ex != null) { message += ex.Message; message += Environment.NewLine; Exception originalException = ex.GetOriginalException(); if (originalException != null) { if (originalException.Message != ex.Message) { message += originalException.Message; message += Environment.NewLine; } } message += ex.StackTrace; message += Environment.NewLine; } return message; } } public static partial class Extensions { public static Exception GetOriginalException(this Exception ex) { if (ex.InnerException == null) return ex; return ex.InnerException.GetOriginalException(); } public static string ParseToString(this object obj) { try { if (obj == null) return string.Empty; else return obj.ToString(); } catch { return string.Empty; } } }

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微信小程序通过保存图片分享到朋友圈的功能实现(小程序生成图片分享)
下一篇:关于微信小程序的选择器(时间,日期,地区)的解析(微信小程序时间段选择器)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~