(实战篇)如何缓存数据
前段时间,也就是去年这个时候开始到现在之前一个月左右,一直在忙一个项目,现在完结了,做下总结。
总体而言涉及的东西挺多,于是打算分而破之,分开总结。
总结之一如标题:如何缓存人员数据,直接上项目,先看实现
(1)global.asax文件的Application_Start事件里布下雷区,采集缓存数据
private void Application_Start(object sender, EventArgs e) { #region 获取缓存 CacheHelp.SetUserData(); CacheHelp.SetMenuData(); #endregion 获取缓存 }
(2)如何缓存数据和获取缓存数据呢?,以SetUserData()为例
public class CacheHelp { public static void SetUserData() { CacheManager.Instance.SetCache("USER", new UserBLL().GetCacheUserTable()); } }
(3) 缓存调用类
public sealed class CacheManager { private static readonly object padlock = new object(); private static IWebCache instance = null; public static IWebCache Instance { get { lock (padlock) { return instance ?? (instance = new WebCache()); } } }
(4) 缓存实现类
----------------
public class WebCache : IWebCache { /// <summary> /// 获取缓存数据 /// </summary> /// <param name="key"></param> /// <returns></returns> public object GetCache(string key) { return FWConfig.CurContext != null ? FWConfig.CurContext.Application[key] : null; } /// <summary> /// 设置缓存数据 /// </summary> /// <param name="key"></param> /// <param name="obj"></param> public void SetCache(string key, object obj) { if (FWConfig.CurContext != null) FWConfig.CurContext.Application[key] = obj; } }
(5) 缓存接口
---------------------
/// <summary> /// 缓存接口 /// </summary> public interface IWebCache { /// <summary> /// 获取缓存 /// </summary> /// <param name="key"></param> /// <returns></returns> object GetCache(string key); /// <summary> /// 设置缓存 /// </summary> /// <param name="key"></param> /// <param name="obj"></param> void SetCache(string key, object obj); }
(6) 提供给页面获取的缓存信息
public class CacheHelp { public static DataTable UserDt { get { DataTable dtOrg = WebCacheManager.Instance.GetApplicationCache("USER") as DataTable; if (dtOrg == null) { SetUserData(); return CacheManager.Instance.GetCache("USER") as DataTable; } else { return CacheManager.Instance.GetCache("USER") as DataTable; } } } }
注: FWConfig.CurContext
public class FWConfig { public static HttpContext CurContext { get {return HttpContext.Current; } }}