1、HttpRuntime.Cache 相當於就是一個緩存具體實現類,這個類雖然被放在了 System.Web 命名空間下了。但是非 Web 應用也是可以拿來用的。 2、HttpContext.Cache 是對上述緩存類的封裝,由於封裝到了 HttpContext ,局限於只能在知道 HttpCon ...
1、HttpRuntime.Cache 相當於就是一個緩存具體實現類,這個類雖然被放在了 System.Web 命名空間下了。但是非 Web 應用也是可以拿來用的。
2、HttpContext.Cache 是對上述緩存類的封裝,由於封裝到了 HttpContext ,局限於只能在知道 HttpContext 下使用,即只能用於 Web 應用。
綜上所屬,在可以的條件,儘量用 HttpRuntime.Cache ,而不是用 HttpContext.Cache 。
Cache有以下幾條緩存數據的規則。
第一,數據可能會被頻繁的被使用,這種數據可以緩存。
第二,數據的訪問頻率非常高,或者一個數據的訪問頻率不高,但是它的生存周期很長,這樣的數據最好也緩存起來。
第三是一個常常被忽略的問題,有時候我們緩存了太多數據,通常在一臺X86的機子上,如果你要緩存的數據超過800M的話,就會出現記憶體溢出的錯誤。所以說緩存是有限的。換名話說,你應該估計緩存集的大小,把緩存集的大小限制在10以內,否則它可能會出問題。
1.cache的創建
cache.Insert(string key,object value,CacheDependency dependencies,DateTime absoluteExpiration,TimeSpan slidingExpiration)//只介紹有5個參數的情況,其實cache里有很幾種重載
參數一:引用該對象的緩存鍵
參數二:要插入緩存中的對象
參數三:緩存鍵的依賴項,當任何依賴項更改時,該對象即無效,並從緩存中移除。 null.">如果沒有依賴項,則此參數包含 null。
參數四:設置緩存過期時間
參數五:參數四的依賴項,如果使用絕對到期,null.">slidingExpiration parameter must beNoSlidingExpiration.">則 slidingExpiration 參數必須為 NoSlidingExpiration
2.銷毀cache
cache.Remove(string key)//key為緩存鍵,通過緩存鍵進行銷毀
3.調用cache
例如你存的是一個DataTable對象,調用如下: DataTable finaltable = Cache["dt"] as DataTable;
4.一般什麼時候選用cache
cache一般用於數據較固定,訪問較頻繁的地方,例如在前端進行分頁的時候,初始化把數據放入緩存中,然後每次分頁都從緩存中取數據,這樣減少了連接資料庫的次數,提高了系統的性能。
/// <summary> /// 獲取數據緩存 /// </summary> /// <param name="cacheKey">鍵</param> public static object GetCache(string cacheKey) { var objCache = HttpRuntime.Cache.Get(cacheKey); return objCache; } /// <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, int timeout = 7200) { try { if (objObject == null) return; var objCache = HttpRuntime.Cache; //相對過期 //objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeout, CacheItemPriority.NotRemovable, null); //絕對過期時間 objCache.Insert(cacheKey, objObject, null, DateTime.Now.AddSeconds(timeout), TimeSpan.Zero, CacheItemPriority.High, null); } catch (Exception) { //throw; } } /// <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; var cacheEnum = cache.GetEnumerator(); while (cacheEnum.MoveNext()) { cache.Remove(cacheEnum.Key.ToString()); } }