ASP.NET HttpRuntime.Cache緩存類使用總結


  1.高性能文件緩存key-value存儲—Redis

  2.高性能文件緩存key-value存儲—Memcached

  備注:三篇博文結合閱讀,簡單理解並且使用,如果想深入學習,請多參考文章中給出的博文地址。

1.前言

  a.在Web開發中,我們經常能夠使用到緩存對象(Cache),在ASP.NET中提供了兩種緩存對象,HttpContext.Current.Cache和HttpRuntime.Cache,那么他們有什么區別呢?下面簡單描述一下:

    (1):HttpContext.Current.Cache 為當前Http請求獲取Cache對象,通俗來說就是由於此緩存封裝在了HttpContenxt中,而HttpContext只局限於Web中,所以此緩存信息只能夠在Web中使用。

    (2):HttpRuntime.Cache 獲取當前應用程序的Cache,通俗來說就是此緩存信息雖然被放在了System.Web命名空間下,但是非Web程序也可以使用此緩存。

    上面兩種類型作對比,我們就能夠看出,一般情況下我們都建議使用HttpRuntime.Cache 。

  b.在緩存領域中,現在不止只有ASP.NET提供的緩存,還有Redis和Memcached等開源的Key_Value存儲系統,也是基於內存去管理的,那么我們在這些文章中基本也都會有說到。

  c.那么這篇文章我們就簡單的封裝一下HttpRuntime.Cache類的公用類,提供給別人直接使用,如有錯誤或者問題,請留言,必在第一時間去處理。

  d.緩存詳解:http://www.cnblogs.com/caoxch/archive/2006/11/20/566236.html

  e.GitHub地址:https://github.com/kencery/Common/tree/master/KenceryCommonMethod/%E7%BC%93%E5%AD%98

2.為什么使用緩存

  a.那么說了這么多,最終要的一個問題是我們為什么要使用緩存呢?

    (1):降低延遲,使響應速度加快。

    (2):降低網絡傳輸,使響應速度加快。

    ...........................

    簡單總結就是一句話,使用緩存是為了使系統更加穩定和快速。

  b.上面我們知道了為什么使用緩存,那么在什么情況下我們能夠使用緩存呢?

    (1):數據可能會被頻繁的使用。

    (2):數據的訪問不頻繁,但是它的生命周期很長,這樣的數據建議也緩存起來,比如:淘寶的商品明細。

    ......................

  c.當然一般系統中我們建議使用Memcached和Redis鍵值對來存儲緩存信息。

  d.那么是不是我們在寫程序的時候想寫緩存就寫緩存呢?當然不是,我們還要判斷哪里該用,哪里不該用,比如:如果我們整頁輸出緩存的話,會影響我們數據的更新等等.......

  e.這篇博文我們整理了HttpRuntime Cache的共同類,將如何使用此類都已經在代碼中展示出來,代碼如下:

3.代碼展示

  1 // 源文件頭信息:
  2 // <copyright file="HttpRuntimeCache.cs">
  3 // Copyright(c)2014-2034 Kencery.All rights reserved.
  4 // 個人博客:http://www.cnblogs.com/hanyinglong
  5 // 創建人:韓迎龍(kencery)
  6 // 創建時間:2015-8-11
  7 // </copyright>
  8 
  9 using System;
 10 using System.Collections;
 11 using System.Web;
 12 using System.Web.Caching;
 13 
 14 namespace KenceryCommonMethod
 15 {
 16     /// <summary>
 17     /// HttpRuntime Cache讀取設置緩存信息封裝
 18     /// <auther>
 19     ///     <name>Kencery</name>
 20     ///     <date>2015-8-11</date>
 21     /// </auther>
 22     /// 使用描述:給緩存賦值使用HttpRuntimeCache.Set(key,value....)等參數(第三個參數可以傳遞文件的路徑(HttpContext.Current.Server.MapPath()))
 23     /// 讀取緩存中的值使用JObject jObject=HttpRuntimeCache.Get(key) as JObject,讀取到值之后就可以進行一系列判斷
 24     /// </summary>
 25     public class HttpRuntimeCache
 26     {
 27         /// <summary>
 28         /// 設置緩存時間,配置(從配置文件中讀取)
 29         /// </summary>
 30         private const double Seconds = 30*24*60*60;
 31 
 32         /// <summary>
 33         /// 緩存指定對象,設置緩存
 34         /// </summary>
 35         public static bool Set(string key, object value)
 36         {
 37             return Set(key, value, null, DateTime.Now.AddSeconds(Seconds), Cache.NoSlidingExpiration,
 38                 CacheItemPriority.Default, null);
 39         }
 40 
 41         /// <summary>
 42         ///  緩存指定對象,設置緩存
 43         /// </summary>
 44         public static bool Set(string key, object value, string path)
 45         {
 46             try
 47             {
 48                 var cacheDependency = new CacheDependency(path);
 49                 return Set(key, value, cacheDependency);
 50             }
 51             catch
 52             {
 53                 return false;
 54             }
 55         }
 56 
 57         /// <summary>
 58         /// 緩存指定對象,設置緩存
 59         /// </summary>
 60         public static bool Set(string key, object value, CacheDependency cacheDependency)
 61         {
 62             return Set(key, value, cacheDependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
 63                 CacheItemPriority.Default, null);
 64         }
 65 
 66         /// <summary>
 67         /// 緩存指定對象,設置緩存
 68         /// </summary>
 69         public static bool Set(string key, object value, double seconds, bool isAbsulute)
 70         {
 71             return Set(key, value, null, (isAbsulute ? DateTime.Now.AddSeconds(seconds) : Cache.NoAbsoluteExpiration),
 72                 (isAbsulute ? Cache.NoSlidingExpiration : TimeSpan.FromSeconds(seconds)), CacheItemPriority.Default,
 73                 null);
 74         }
 75 
 76         /// <summary>
 77         /// 獲取緩存對象
 78         /// </summary>
 79         public static object Get(string key)
 80         {
 81             return GetPrivate(key);
 82         }
 83 
 84         /// <summary>
 85         /// 判斷緩存中是否含有緩存該鍵
 86         /// </summary>
 87         public static bool Exists(string key)
 88         {
 89             return (GetPrivate(key) != null);
 90         }
 91 
 92         /// <summary>
 93         /// 移除緩存對象
 94         /// </summary>
 95         /// <param name="key"></param>
 96         /// <returns></returns>
 97         public static bool Remove(string key)
 98         {
 99             if (string.IsNullOrEmpty(key))
100             {
101                 return false;
102             }
103             HttpRuntime.Cache.Remove(key);
104             return true;
105         }
106 
107         /// <summary>
108         /// 移除所有緩存
109         /// </summary>
110         /// <returns></returns>
111         public static bool RemoveAll()
112         {
113             IDictionaryEnumerator iDictionaryEnumerator = HttpRuntime.Cache.GetEnumerator();
114             while (iDictionaryEnumerator.MoveNext())
115             {
116                 HttpRuntime.Cache.Remove(Convert.ToString(iDictionaryEnumerator.Key));
117             }
118             return true;
119         }
120 
121         //------------------------提供給上面方法進行調用-----------------------------------
122         /// <summary>
123         /// 設置緩存
124         /// </summary>
125         public static bool Set(string key, object value, CacheDependency cacheDependency, DateTime dateTime,
126             TimeSpan timeSpan, CacheItemPriority cacheItemPriority, CacheItemRemovedCallback cacheItemRemovedCallback)
127         {
128             if (string.IsNullOrEmpty(key) || value == null)
129             {
130                 return false;
131             }
132             HttpRuntime.Cache.Insert(key, value, cacheDependency, dateTime, timeSpan, cacheItemPriority,
133                 cacheItemRemovedCallback);
134             return true;
135         }
136 
137         /// <summary>
138         /// 獲取緩存
139         /// </summary>
140         private static object GetPrivate(string key)
141         {
142             return string.IsNullOrEmpty(key) ? null : HttpRuntime.Cache.Get(key);
143         }
144     }
145 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM