通常我們針對頁面以及相關數據進行相應的緩存(分為客戶端和服務端的緩存),以下代碼為對一般操作 進行相應的緩存(服務端),用以減少對數據庫的訪問次數,減少服務器的壓力。
(一)CacheHelper 類
CacheHelper類主要是依賴於系統的System.Web.Caching.HostingEnvironment.Cache,具體代碼如 下:
public static class CacheHelper { private static Cache _cache; public static double SaveTime { get; set; } static CacheHelper() { _cache = HostingEnvironment.Cache; SaveTime = 15.0; } public static object Get(string key) { if (string.IsNullOrEmpty(key)) { return null; } return _cache.Get(key); } public static T Get<T>(string key) { object obj = Get(key); return obj==null?default(T):(T)obj; } public static void Insert(string key, object value, CacheDependency dependency, CacheItemPriority priority, CacheItemRemovedCallback callback) { _cache.Insert(key, value, dependency, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(SaveTime), priority, callback); } public static void Insert(string key, object value, CacheDependency dependency, CacheItemRemovedCallback callback) { Insert(key, value, dependency, CacheItemPriority.Default, callback); } public static void Insert(string key, object value, CacheDependency dependency) { Insert(key, value, dependency, CacheItemPriority.Default, null); } public static void Insert(string key, object value) { Insert(key, value, null, CacheItemPriority.Default, null); } public static void Remove(string key) { if (string.IsNullOrEmpty(key)) { return; } _cache.Remove(key); } public static IList<string> GetKeys() { List<string> keys = new List<string>(); IDictionaryEnumerator enumerator = _cache.GetEnumerator(); while (enumerator.MoveNext()) { keys.Add(enumerator.Key.ToString()); } return keys.AsReadOnly(); } public static void RemoveAll() { IList<string> keys = GetKeys(); foreach (string key in keys) { _cache.Remove(key); } } } }
在原有基礎上增加了如下3個方法:
(1)public static T Get<T>(string key)
(2)public static IList<string> GetKeys()
(3)public static void RemoveAll ()
這樣我們能夠方便的以靜態方法來對Cache進行相應的操作。