/// <summary> /// 添加统计 /// </summary> /// <param name="sql">dbBuilder.ToString():唯一标识</param> /// <param name="dataType">数据类型</param> private static string CreateKey(string sql, enumDataType dataType) { #region 移除失效时间 // 移除失效的时间 DataStatisticsList.ForEach(o => o.LstActiveAt.RemoveAll(t => DateTime.Now > t.AddMinutes(CacheConfigs.ConfigInfo.VisitTime))); // 移除无时间统计的项 DataStatisticsList.RemoveAll(o => o.Value == null && o.LstActiveAt.Count() == 0); // 重置加入缓存时间 var lst = DataStatisticsList.Where(o => o.Value == null).ToList(); for (var i = 0; i < lst.Count; i++) { lst[i].JoinCacheAt = DateTime.MinValue; } #endregion var key = Encrypt.MD5(dataType.GetName() + sql).Substring(8, 16); // 加入统计 var cache = DataStatisticsList.FirstOrDefault(o => o.Key == key); if (cache == null) { cache = new DataCache { Key = key, DataType = dataType, LstActiveAt = new List <DateTime>() }; DataStatisticsList.Add(cache); } cache.LstActiveAt.Add(DateTime.Now); return(key); }
/// <summary> /// 添加缓存值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="t">dbBuilder.ToString():唯一标识</param> /// <param name="isIgnoreStatistics">是否忽略统计,直接加入缓存</param> private static void Set <T>(string key, T t, bool isIgnoreStatistics = false) { var cache = DataStatisticsList.FirstOrDefault(o => o.Key == key); if (!isIgnoreStatistics && cache.LstActiveAt.Count < CacheConfigs.ConfigInfo.VisitCount) { return; } // 加入缓存 WebCache.Add(key, t, CacheConfigs.ConfigInfo.CacheTimeOut); cache.JoinCacheAt = DateTime.Now; }
/// <summary> /// 获取缓存值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">dbBuilder.ToString():唯一标识</param> public static T Get <T>(string sql, enumDataType dataType, Func <T> func = null, bool isIgnoreStatistics = false) { var key = CreateKey(sql, dataType); var value = DataStatisticsList.FirstOrDefault(o => o.Key == key).Value; if (value == null) { if (func == null) { return(default(T)); } value = func(); Set(key, value, isIgnoreStatistics); } return((T)value); }