這種策略讓緩存依賴于一個指定的文件,通過改變文件的更新日期來清除緩存。
|
/// <summary> /// 獲取當前應(yīng)用程序指定CacheKey的Cache對象值 /// </summary> /// <param name="CacheKey">索引鍵值</param> /// <returns>返回緩存對象</returns> public static object GetCache(string CacheKey) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; return objCache[CacheKey]; } /// <summary> /// 設(shè)置以緩存依賴的方式緩存數(shù)據(jù) /// </summary> /// <param name="CacheKey">索引鍵值</param> /// <param name="objObject">緩存對象</param> /// <param name="cacheDepen">依賴對象</param> public static void SetCache(string CacheKey, object objObject, System.Web.Caching.CacheDependency dep) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; objCache.Insert( CacheKey, objObject, dep, System.Web.Caching.Cache.NoAbsoluteExpiration, //從不過期 System.Web.Caching.Cache.NoSlidingExpiration, //禁用可調(diào)過期 System.Web.Caching.CacheItemPriority.Default, null); } protected void Page_Load(object sender, EventArgs e) { string CacheKey = "cachetest"; object objModel = GetCache(CacheKey);//從緩存中獲取 if (objModel == null) //緩存里沒有 { objModel = DateTime.Now;//把當前時間進行緩存 if (objModel != null) { //依賴 C:\\test.txt 文件的變化來更新緩存 System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency("C:\\test.txt"); SetCache(CacheKey, objModel, dep);//寫入緩存 } } Label1.Text = objModel.ToString(); } |
當我們改變test.txt的內(nèi)容時,緩存會自動更新。這種方式非常適合讀取配置文件的緩存處理。如果配置文件不變化,就一直讀取緩存的信息,一旦配置發(fā)生變化,自動更新同步緩存的數(shù)據(jù)。
這種方式的缺點是,如果緩存的數(shù)據(jù)比較多,相關(guān)的依賴文件比較松散,對管理這些依賴文件有一定的麻煩。對于負載均衡環(huán)境下,還需要同時更新多臺Web服務(wù)器下的緩存文件,如果多個Web應(yīng)用中的緩存依賴于同一個共享的文件,可能會省掉這個麻煩。
浙公網(wǎng)安備 33010602011771號