一.缓存:
- 5个等级的缓存
- 1级是网络级缓存,缓存在浏览器,CDN以及代理服务器中 (举个例子:每个帮助页面都进行了缓存,访问一个页面的代码非常简单)
- 2级是由.net框架 HttpRuntime.Cache完成,在每台服务器的内存中。
- 3级Redis,分布式内存键值存储,在多个支撑同一个站点的服务器上共享缓存项。
- 4级SQL Server Cache,整个数据库,所有数据都被放到内存中。
- 5级SSD。通常只在SQL Server预热后才生效
二.具体使用
添加cachehelper类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// 缓存帮助类 /// 时间:2016/05/07 /// </summary> public class CacheHelper { #region 获取数据缓存 /// <summary> /// 获取数据缓存 /// </summary> /// <param name="cacheKey">键</param> /// <param name="objObject"></param> public static object GetCache(string cacheKey) { var objCache = HttpRuntime.Cache; return objCache[cacheKey]; } #endregion #region 设置数据缓存 /// <summary> /// 设置数据缓存 /// </summary> public static void SetCache(string cacheKey, object objObject) { var objCache = HttpRuntime.Cache; objCache.Insert(cacheKey, objObject); } /// <summary> /// 设置数据缓存 /// </summary> public static void SetCache(string cacheKey, object objObject, TimeSpan timeout) { var objCache = HttpRuntime.Cache; objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeout, CacheItemPriority.NotRemovable, null); } /// <summary> /// 设置数据缓存 /// </summary> public static void SetCache(string cacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration) { var objCache = HttpRuntime.Cache; objCache.Insert(cacheKey, objObject, null, absoluteExpiration, slidingExpiration); } #endregion #region 移除缓存 /// <summary> /// 移除指定数据缓存 /// </summary> public static void RemoveAllCache(string cacheKey) { var cache = HttpRuntime.Cache; cache.Remove(cacheKey); } /// <summary> /// 移除全部缓存 /// </summary> public static void RemoveAllCache() { var cache = HttpRuntime.Cache; IDictionaryEnumerator cacheEnum = cache.GetEnumerator(); while (cacheEnum.MoveNext()) { cache.Remove(cacheEnum.Key.ToString()); } } #endregion }
添加完对此进行调用先判断是否已经cache没有则添加
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
var cacheKey = "sid" + assessId + "uid" + studentId + "pindex" + pageHelper.PageIndex; var cachelist = CacheHelper.GetCache(cacheKey) as List<Question>; if (cachelist != null) { return cachelist; } 获取数据 var result = GetAssessQuseList(pageHelper, tableName, fields, null, orderBy, true, studentId, otherFields); CacheHelper.SetCache(cacheKey, result, TimeSpan.FromSeconds(120)); return result;
下面是移除cache
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
var cacheKey = "sid" + assessId + "uid" + base.LoggingUser.UserId + "pindex" + pageIndex; var cachelist = CacheHelper.GetCache(cacheKey) as List<Question>; if (cachelist != null) { CacheHelper.RemoveAllCache(cacheKey); }