天天看點

緩存依賴(檔案、資料庫)

前言

緩存的基本用法介紹:我推薦看下  asp.net緩存 。

本篇,我主要寫下一般sql的緩存依賴,還有使用Mvc過濾器的資料庫緩存依賴。

什麼是緩存依賴

1.緩存:是把你要通路的資源,放在記憶體中,占用一定的記憶體空間,進而是使用者讀取記憶體中的資料,進而減少讀取資料庫,或資源檔案的次數,進而對你的程式并發量,以及傳回請求速率上得到提高的一種機制。

2.緩存的不及時性:由于在緩存的作用時間内,資料放在記憶體中,不知道資料源是否已經改變,進而是資訊失去即時效應。

3.解決不及時性:為啦解決第二條的不及時性,微軟想到的就是緩存依賴

4.緩存依賴:就是緩存通過監測依賴項(檔案或資料庫)的讀寫,來通知緩存是否過期的一種機制。比如,依賴項是123.txt檔案,緩存的資料是234.txt中的資料,那麼緩存機制可通過監測123.txt檔案中資料的是否變化,來移除緩存234.txt檔案的資料。感覺扯淡,還是上代碼更給力。

緩存依賴項(檔案)

//檔案緩存依賴
            if (cache.Get("key") == null)//如果依賴項中的資料發生變化,此會被通知緩存清空(系統完成清空)
            {
                CacheDependency dp = new CacheDependency(Server.MapPath("/Data/123.txt"));//建立緩存依賴項dp
                string str = DoIOFile.ReadFiles("/Data/111.txt");
                cache.Insert("key", str, dp);
            }
            Response.Write(cache.Get("key"));   //如果123.txt這個檔案的内容不變就一直讀取緩存中的資料,一旦123.txt檔案中的資料改變裡面重新讀取111.txt檔案中的資料      

效果:緩存的資料是111.txt中的資料,111.txt中的資料發生變化,鑰匙為key的緩存不會被清空,也就是依舊顯示沒改前的資料。但是如果緩存依賴項123.txt中的資料一旦發生變化,緩存立馬被清空,重新寫入緩存中新的資料。這就是緩存依賴的好處,你可以試下,我不忽悠你。

緩存依賴項(檔案夾)

//檔案夾緩存依賴
            if (cache.Get("key") == null)//如果依賴項中的資料發生變化,此會被通知緩存清空(系統完成清空)
            {
                CacheDependency dp = new CacheDependency(Server.MapPath("/Data"));//建立緩存依賴項dp 
                string str = DoIOFile.ReadFiles("111.txt");
                cache.Insert("key", str, dp);
            }
            Response.Write(cache.Get("key"));   //如果123.txt這個檔案的内容不變就一直讀取緩存中的資料,一旦123.txt檔案中的資料改變裡面重新讀取111.txt檔案中的資料      

效果:這裡/Data是個檔案夾,他下面直屬Data所有一級檔案(就是不能算嵌套檔案夾的檔案)如果有變動,都會觸發通知,清空緩存。

緩存依賴項(多檔案)

//多檔案依賴項
            if (cache.Get("key") == null)//如果依賴項中的資料發生變化,此會被通知緩存清空(系統完成清空)
            {
                CacheDependency dp1 = new CacheDependency(Server.MapPath("/Data/123/123.txt")); //這裡是監視檔案或目錄
                CacheDependency dp2 = new CacheDependency(Server.MapPath("/Data/123.txt"));

                CacheDependency[] dps = new CacheDependency[] { dp1, dp2 };
                AggregateCacheDependency aDp = new AggregateCacheDependency(); //多個依賴項
                aDp.Add(dps);
                string str = DoIOFile.ReadFiles("111.txt");
                cache.Insert("key", str, aDp);
            }
            Response.Write(cache.Get("key"));        

效果:依賴項中的任何一個檔案有變動,緩存清空,寫入新緩存。

Mvc中的緩存

mvc中緩存的使用方法相對來說比較簡單,隻用在過濾器上定義一下就行啦,其它的我就不累述啦,與webForm無異。

[OutputCache(Duration = 20)] //定義緩存,秒為機關,Duration是必填項
        public ActionResult Index()
        {
            string str = DoIOFile.ReadFiles("/111.txt");
            Response.Write(str);
            return View();
        }      

具體配置詳見:http://msdn.microsoft.com/zh-cn/library/system.web.mvc.outputcacheattribute.aspx

緩存依賴(資料庫表)

這個多少有點繁瑣,跟着做。

1.打開項目配置檔案

<connectionStrings>     
    <add name="Am_WeixinWeb" connectionString="data source=192.168.1.200;initial catalog=Am_WeixinWeb;uid=sa;password=lh1234;"  />
  </connectionStrings>      
<system.web>
    <caching>
      <sqlCacheDependency enabled="true" pollTime="2000">
        <databases>
          <add name="Test" connectionStringName="Am_WeixinWeb" />
        </databases>
      </sqlCacheDependency>
    </caching>      

注記:pollTime,毫秒為機關,意識是每隔2秒檢測下資料庫,檢測表是否有發生變化。connectionStringName為資料庫連結字元串。

2.啟動資料庫緩存依賴

在C槽中,搜尋到工具aspnet_regsql.exe

在指令中 cd:運作到此工具的檔案下,鍵入下面指令

aspnet_regsql -C "data source=;initial catalog=codematic;user id=sa;password=" -ed -et -t "T_table"  

緩存依賴(檔案、資料庫)

參數:-c 後跟連接配接字元串,-t後接建立緩存依賴的表名

工具指令參數清單詳見:http://msdn.microsoft.com/zh-cn/library/ms229862

3.使用緩存依賴項

//sql緩存依賴
            DataSet ds = new DataSet();
            if (cache.Get("key") == null)
            {
                string conStr = DoXml.ReadWebConfigConnectionStrings("Am_WeixinWeb");
                SqlConnection conn = new SqlConnection(conStr);
                string sql = "select top(1) recContent from Am_recProScheme";
                SqlCommand cmd = new SqlCommand(sql, conn);
                SqlDataAdapter sda = new SqlDataAdapter(cmd);

                sda.Fill(ds, "tb1");
                SqlCacheDependency dep = new SqlCacheDependency("Test", "Am_recProScheme");  //Test對應配置項的緩存配置key ,後面是資料庫表名
                cache.Insert("key", ds.Tables["tb1"].Rows[0]["recContent"].ToString(), dep);
            }
            Response.Write(cache.Get("key"));      

效果:資料庫Am_WeixinWeb中表Am_recProScheme中的資料有所變動,則清空緩存,重新寫入。

Mvc過濾器中配置緩存依賴(資料庫)

<connectionStrings>    
    <add name="Am_WeixinWeb" connectionString="data source=192.168.1.200;initial catalog=Am_WeixinWeb;uid=sa;password=lh1234;"  />
  </connectionStrings>      
<caching>
      <sqlCacheDependency enabled="true" pollTime="2000">
        <databases>
          <add name="Test" connectionStringName="Am_WeixinWeb" />
        </databases>
      </sqlCacheDependency>
    </caching>      

2.配置過濾器 

//mvc緩存依賴
        [OutputCache(Duration = 20, SqlDependency = "Test:Am_recProScheme")] //Test:為緩存配置的key,後面跟的是緩存依賴表
        public ActionResult Index()
        {           
            Response.Write(db.Am_recProScheme.FirstOrDefault().recContent);
            return View();
        }       

效果:資料庫Am_WeixinWeb中表Am_recProScheme中的資料有所變動,則清空緩存,重新寫入。

本文以實用簡略為主,如有探讨,可加左上方技術交流群,謝謝閱讀,願能給你一點點幫助。