緩存依賴(文件、數據庫)

前言

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

本篇,我主要寫下通常sql的緩存依賴,還有使用Mvc過濾器的數據庫緩存依賴。web

什麼是緩存依賴

1.緩存:是把你要訪問的資源,放在內存中,佔用必定的內存空間,從而是用戶讀取內存中的數據,進而減小讀取數據庫,或資源文件的次數,從而對你的程序併發量,以及返回請求速率上獲得提升的一種機制。sql

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中的數據一旦發生變化,緩存立馬被清空,從新寫入緩存中新的數據。這就是緩存依賴的好處,你能夠試下,我不忽悠你。mvc

緩存依賴項(文件夾)

            //文件夾緩存依賴
            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全部一級文件(就是不能算嵌套文件夾的文件)若是有變更,都會觸發通知,清空緩存。asp.net

緩存依賴項(多文件)

            //多文件依賴項
            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無異。ui

        [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過濾器中配置緩存依賴(數據庫)

1.打開項目配置文件

 <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>

註記:pollTime,毫秒爲單位,意識是每隔2秒檢測下數據庫,檢測表是否有發生變化。connectionStringName爲數據庫連接字符串。

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中的數據有所變更,則清空緩存,從新寫入。

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

相關文章
相關標籤/搜索