系統快取全解析5:檔案快取依賴

iDotNetSpace發表於2009-07-02

 這種策略讓快取依賴於一個指定的檔案,通過改變檔案的更新日期來清除快取。

                                               

/// 

/// 獲取當前應用程式指定CacheKeyCache物件值

/// 

/// 索引鍵值

/// 返回快取物件

public static object GetCache(string CacheKey)

{

    System.Web.Caching.Cache objCache = HttpRuntime.Cache;

    return objCache[CacheKey];

}

/// 

/// 設定以快取依賴的方式快取資料

/// 

/// 索引鍵值

/// 快取物件

/// 依賴物件

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, //禁用可調過期

        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 = newSystem.Web.Caching.CacheDependency("C:\\test.txt");

            SetCache(CacheKey, objModel, dep);//寫入快取

        }

    }

 

    Label1.Text = objModel.ToString();

}

    當我們改變test.txt的內容時,快取會自動更新。這種方式非常適合讀取配置檔案的快取處理。如果配置檔案不變化,就一直讀取快取的資訊,一旦配置發生變化,自動更新同步快取的資料。

這種方式的缺點是,如果快取的資料比較多,相關的依賴檔案比較鬆散,對管理這些依賴檔案有一定的麻煩。對於負載均衡環境下,還需要同時更新多臺Web伺服器下的快取檔案,如果多個Web應用中的快取依賴於同一個共享的檔案,可能會省掉這個麻煩。 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-608134/,如需轉載,請註明出處,否則將追究法律責任。

相關文章