緩存是將信息放在內存中以免頻繁訪問數據庫從數據庫中提取數據,在系統優化過程當中,緩存是比較廣泛的優化作法和見效比較快的作法。web
對於MVC有Control緩存和Action緩存。sql
1、Control緩存數據庫
Control緩存便是把緩存應用到整個Control上,該Control下的全部Action都會被緩存起來。緩存
咱們來看一下例子:ide
[OutputCache(Duration = 10)] public class HomeController : Controller { // GET: Home public ActionResult Index() { ViewBag.CurrentTime = DateTime.Now; return View(); } }
view中:工具
@{ ViewBag.Title = "Index"; } <h2>@ViewBag.CurrentTime</h2>
效果:優化
不停的刷新頁面,時間會每10秒鐘更新一次。ui
2、Action緩存spa
將緩存加載Action上,這樣,只有加緩存的Action纔會有緩存,其餘的Action沒有。code
寫法與Control的緩存同樣。
//Action緩存,10秒 [OutputCache(Duration = 10)] // GET: Home public ActionResult Index() { ViewBag.CurrentTime = DateTime.Now; return View(); } public ActionResult Index2() { ViewBag.CurrentTime = DateTime.Now; return View(); }
這裏分別有兩個Action,一個加了緩存的Index,還有一個沒有加緩存的Index2
效果:
分別訪問這兩個頁面,不停的刷新這兩個頁面,Index 中的時間會10秒鐘更新一次,而Index2中會實時更新。
3、使用配置文件進行緩存配置
在MVC的Web.config文件中,能夠對緩存進行相關的配置。
在system.web節點中,添加caching子節點,而後以下:
<outputCacheSettings> <outputCacheProfiles> <add name="TestConfigCache" duration="10" /> </outputCacheProfiles> </outputCacheSettings>
配置好後,咱們的Control緩存或者Action緩存就能夠這麼寫:
[OutputCache(CacheProfile= "TestConfigCache")] // GET: Home public ActionResult Index() { ViewBag.CurrentTime = DateTime.Now; return View(); }
4、緩存依賴
緩存數據是從數據庫中某個表獲取的,若是數據庫中對應的表的數據沒有發生改變,咱們就沒有必要對緩存數據進行更新,若是數據庫對應的表的數據發生了變化,那麼,咱們相應的緩存數據就應當即更新。
那麼緩存是否過時,依賴於數據庫對應的表中的數據是否發生變化。這就是緩存依賴。下面咱們來寫一下。
咱們MVC的Web.config文件中進行以下未配置:
一、首先配置數據庫鏈接字符串:
<connectionStrings> <add name="sqlCon" connectionString="server=127.0.0.1;database=test;uid=sa;pwd=123456" providerName="System.Data.SqlClient" /> </connectionStrings>
二、進行緩存依賴配置:
<caching> <sqlCacheDependency> <databases> <add name="PersonCacheDependency" connectionStringName="sqlCon" pollTime="500"/> </databases> </sqlCacheDependency> <outputCacheSettings> <outputCacheProfiles> <add name="TestConfigCache" duration="3600" sqlDependency="PersonCacheDependency:Person"/> </outputCacheProfiles> </outputCacheSettings> </caching>
其中pollTime爲監聽數據庫變化的間隔時間(毫秒)
以上配置說明:庫名:test,監聽表名:Person。緩存時間爲:3600秒即一小時。數據庫依賴週期爲500毫秒,即每0.5秒監聽下數據庫是否有變化,若是有變化則當即更新緩存。
Control中或Action中:
[OutputCache(CacheProfile= "TestConfigCache")] // GET: Home public ActionResult Index() { ViewBag.CurrentTime = DateTime.Now; return View(); }
這樣,在一個小時內,只有Person表中的數據發生變化後,緩存纔會更新,否則緩存不會更新。
5、注:
當咱們配置完緩存以來後,運行咱們的項目,可能會出現一下錯誤提示:
這是由於咱們沒有對Person表啓用緩存通知。
打開vs命令工具行,輸入:aspnet_regsql -S localhost -U sa -P 123456 -ed -d test-et -t Person
這樣就能夠解決上述錯誤。
好了,MVC的緩存就介紹到這裏。見識淺薄,有不當之處,還望大神們指點一二。