C#数据源缓存
调用:
public List<ReRank> GetBoZhuRank(int category) { return CacheHelper.TryGet("GetBoZhuRank" + category, () => { try { return new BLL.CastRoomApi(webEntity).GetCastRoomRankList(category).Data; //调用接口获取数据 } catch (Exception ex) { LogUtlilty.WriteLog(string.Format("错误:{0}", ex.Message), LogUtlilty.Level.ERROR); } return new List<ReRank>(); }, DateTime.Now.AddMinutes(2), new List<ReRank>()); //缓存2分钟 }
CacheHelper帮助类:
using System; using System.Web; using System.Collections; namespace LiveCast.Web.Common.Utility { public class CacheHelper { /// <summary> /// 获取数据缓存 /// </summary> /// <param name="CacheKey">键</param> public static object GetCache(string CacheKey) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; return objCache[CacheKey]; } /// <summary> /// 设置数据缓存 /// </summary> public static void SetCache(string CacheKey, object objObject) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; objCache.Insert(CacheKey, objObject); } /// <summary> /// 设置数据缓存 /// </summary> public static void SetCache(string CacheKey, object objObject, TimeSpan Timeout) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; objCache.Insert(CacheKey, objObject, null, DateTime.MaxValue, Timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null); } /// <summary> /// 设置数据缓存 /// </summary> public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration); } /// <summary> /// 移除指定数据缓存 /// </summary> public static void RemoveAllCache(string CacheKey) { System.Web.Caching.Cache _cache = HttpRuntime.Cache; _cache.Remove(CacheKey); } /// <summary> /// 移除全部缓存 /// </summary> public static void RemoveAllCache() { System.Web.Caching.Cache _cache = HttpRuntime.Cache; IDictionaryEnumerator CacheEnum = _cache.GetEnumerator(); while (CacheEnum.MoveNext()) { _cache.Remove(CacheEnum.Key.ToString()); } }
public static object Get(string key, Func<object> getValueFunc, DateTime absoluteExpiration) { var val = GetCache(key); if (val == null) { val = getValueFunc(); if (val != null) { SetCache(key, val, absoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration); } } return val; } public static TResult TryGet<TResult>(string key, Func<TResult> getValueFunc, DateTime absoluteExpiration, TResult defaultVal) { TResult result; try { var val = Get(key, () => getValueFunc(), absoluteExpiration); if (val == null) { val = defaultVal; } result = (TResult)val; } catch (Exception ex) { result = defaultVal; LogUtlilty.WriteLog(string.Format("Cache中异常:{0}", ex.Message), LogUtlilty.Level.ERROR); } return result; } } }

浙公网安备 33010602011771号