mvc 緩存 sqlCacheDependency 監聽數據變化
對於MVC有Control緩存和Action緩存。
一、Control緩存
Control緩存即是把緩存應用到整個Control上,該Control下的所有Action都會被緩存起來。
[OutputCache(Duration = 10)] public class HomeController : Controller { // GET: Home public ActionResult Index() { ViewBag.CurrentTime = DateTime.Now; return View(); } }
@{ ViewBag.Title = "Index"; } <h2>@ViewBag.CurrentTime</h2>
不停的刷新頁面,時間會每10秒鐘更新一次。
二、Action緩存
將緩存加載Action上,這樣,只有加緩存的Action才會有緩存,其他的Action沒有。
三、使用配置文件進行緩存配置
在MVC的Web.config文件中,可以對緩存進行相關的配置。
在system.web節點中,添加caching子節點,然後如下:
<outputCacheSettings> <outputCacheProfiles> <add name="TestConfigCache" duration="10" /> </outputCacheProfiles> </outputCacheSettings>
[OutputCache(CacheProfile= "TestConfigCache")] // GET: Home public ActionResult Index() { ViewBag.CurrentTime = DateTime.Now; return View(); }
四、緩存依賴
緩存數據是從數據庫中某個表獲取的,如果數據庫中對應的表的數據沒有發生改變,我們就沒有必要對緩存數據進行更新,如果數據庫對應的表的數據發生了變化,那麽,我們相應的緩存數據就應立即更新。
那麽緩存是否過期,依賴於數據庫對應的表中的數據是否發生變化。這就是緩存依賴。下面我們來寫一下。
我們MVC的Web.config文件中進行如下未配置:
1、首先配置數據庫連接字符串:
<connectionStrings> <add name="sqlCon" connectionString="server=127.0.0.1;database=test;uid=sa;pwd=123456" providerName="System.Data.SqlClient" /> </connectionStrings>
2、進行緩存依賴配置:
<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表中的數據發生變化後,緩存才會更新,不然緩存不會更新。
五、註:
當我們配置完緩存以來後,運行我們的項目,可能會出現一下錯誤提示:
這是因為我們沒有對Person表啟用緩存通知。
打開vs命令工具行,輸入:aspnet_regsql -S localhost -U sa -P 123456 -ed -d test-et -t Person
mvc 緩存 sqlCacheDependency 監聽數據變化