.NET MVC中緩存的使用


使用緩存可以提高網站性能,減輕對數據庫的壓力,提高用戶訪問網站的速度。在.NET MVC中,我們可以使用輸出緩存和數據緩存達到儲存常用且不易改變的數據。

輸出緩存:

在Action前添加[OutputCache]標簽:

[OutputCache(Duration = 600)]
public ActionResult Content(string code, int ID)
{
    //
    return View();
}

常用參數說明:

Duration:緩存時間,通常情況下是必須的,以秒為單位。

Location:頁面緩存位置,默認為Any(緩存在瀏覽器、代理服務器端、Web服務器端),當被設置為None(不進行緩存)時,可不設置Duration。

VaryByParam:向Action傳參時,根據哪些參數對輸出進行緩存。

//只當傳入的code不同時,會緩存不同的輸出
[OutputCache(Duration = 600, VaryByParam = "code")]
public ActionResult PositionTree(String code, int ID)
//對所有傳入參數進行不同的緩存
[OutputCache(Duration = 600, VaryByParam = "*")]
//緩存與參數無關,此Action只緩存一份
[OutputCache(Duration = 600, VaryByParam = "none")]

CacheProfile:設置此Action關聯的緩存設置名稱,緩存設置寫在Web.config中。

[OutputCache(CacheProfile = "ServerOnly")]
<caching>
    <outputCacheSettings>
        <outputCacheProfiles>
            <add name="ServerOnly" duration="60" location="Server" />
        </outputCacheProfiles>
    </outputCacheSettings>
</caching> 

 

數據緩存:

使用HttpContext.Cache:

HttpContext.Cache["key"] = "value";

Cache和Application類似,為應用程序級(Session為用戶會話級),采用鍵(string)值(Object)對存儲數據。

如何添加Cache:

// 將指定項添加到 System.Web.Caching.Cache 對象,該對象具有依賴項、過期和優先級策略
// 以及一個委托(可用於在從 Cache 移除插入項時通知應用程序)。
HttpContext.Cache.Add(key, value,dependencies,absoluteExpiration,slidingExpiration,priority,onRemoveCallback);
// 從 System.Web.Caching.Cache 對象檢索指定項。
// key: 要檢索的緩存項的標識符。
// 返回結果: 檢索到的緩存項,未找到該鍵時為 null。
HttpContext.Cache.Insert(key,value);
// 同Cache.Insert
HttpContext.Cache[key] = value;
//參數說明:
//key:用於引用該對象的緩存鍵。
//value:要插入緩存中的對象。
//dependencies:該項的文件依賴項或緩存鍵依賴項。當任何依賴項更改時,該對象即無效,
//    並從緩存中移除。如果沒有依賴項,則此參數包含 null。
//absoluteExpiration:所插入對象將過期並被從緩存中移除的時間。
//    如果使用絕對過期,則 slidingExpiration 參數必須為Cache.NoSlidingExpiration。    
//slidingExpiration:最后一次訪問所插入對象時與該對象過期時之間的時間間隔。如果該值等效於 20 分鍾,
//    則對象在最后一次被訪問 20 分鍾之后將過期並被從緩存中移除。如果使用可調過期,則
//    absoluteExpiration 參數必須為System.Web.Caching.Cache.NoAbsoluteExpiration。
//priority:該對象相對於緩存中存儲的其他項的成本,由System.Web.Caching.CacheItemPriority 枚舉表示。
//    該值由緩存在退出對象時使用;具有較低成本的對象在具有較高成本的對象之前被從緩存移除。
//onRemoveCallback:在從緩存中移除對象時將調用的委托(如果提供)。
//    當從緩存中刪除應用程序的對象時,可使用它來通知應用程序。

Cache.Add與Cache.Insert的區別:

Cache.Add 需要完整的參數,且當Cache中存在插入的鍵時會出錯。

Cache.Insert 最少需要key和value參數,當Cache存在插入的鍵時會覆蓋掉原先的值。

移除Cache:

HttpContext.Cache.Remove(key);

Cache過期時間設置:

//設置絕對過期時間,slidingExpiration 參數必須為System.Web.Caching.Cache.NoSlidingExpiration
HttpContext.Cache.Insert("key", "value", null, DateTime.Parse("2015-12-31 00:00:00"), Cache.NoSlidingExpiration);
//設置最后一次訪問緩存項與超期時間的間隔,absoluteExpiration 參數必須為System.Web.Caching.Cache.NoAbsoluteExpiration
HttpContext.Cache.Insert("key", "value", null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(60));

 


免責聲明!

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



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