1. 程式人生 > >asp.net緩存 (轉)

asp.net緩存 (轉)

鏈接 http 不變 moved nbsp oca scripts ati 需要

原文地址 http://www.cnblogs.com/knowledgesea/archive/2012/07/10/2530436.html 謝謝

一、緩存概念,緩存的好處、類型。


緩存是一種用空間換取時間的技術,通俗點也就是說把你得到的數據存放在內存中一段時間,在這短時間內服務器不去讀取數據庫、或是真實的數據源,而是讀取你存放在內存中的數據,這裏你會疑惑怎麽設置存放數據,能存放什麽樣子的數據,存放時間的設置,真實數據源數據改變服務器不就讀取存在偏差?別急,下面慢慢會說到的。。

緩存的好處,緩存是網站性能優化不可缺少的一種數據處理機制,他能有效的緩解數據庫壓力,例如,網站每分鐘的點擊率為100萬,如果不使用緩存的靜態頁面,這裏也沒有viewstate的情況下(viewstate會產生大量的字符串,對服務器交互數據是一種壓力,所以一般頁面是要禁用viewstate,采用緩存的),只能是用戶點擊一次該頁面,這個頁面就讀取一次數據庫,這樣給數據庫造成的壓力可想而知,如果這裏我們使用了緩存的話,設置緩存有效期為1分鐘,則這一分鐘只內,點擊100萬次跟點擊一次是一樣的,都是讀取一次數據庫,數據源是被緩存在內存中了。

asp.net中的緩存主要分為:頁面緩存,數據源緩存,自定義數據緩存這三種主要類型。


二、數據緩存


技術分享圖片
  public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //  Cache["date"]=要緩存的數據;   這裏是自定義緩存的簡單聲明使用
            string datastr = DateTime.Now.ToLongTimeString();
            Response.Write("第一個輸出時間:"+datastr+"</br>");  //這裏讀取的當前的時間,刷新頁面時,這裏的時間會隨著變化。

            if (Cache["date"] == null) //判斷是否存在value值為date的緩存是否存在
            {
                Cache["date"] = datastr;
                Response.Write("第二個輸出時間為:"+Cache["date"] + "這裏讀取的當前的時間");   //這裏讀取的當前的時間,刷新頁面時,這裏的時間會隨著變化。
            }
            else
            {
                Response.Write(Cache["date"] + "這裏是從緩存中讀取的時間");//這裏讀取的緩存中的時間,刷新頁面時,這裏的隨著時間變化,不會變化。
            }
        }
    }
技術分享圖片

上面數據緩存由於沒有設置緩存的過期時間,所以第一個輸出時間為當前時間(刷新頁面會變),第二個輸出時間會一直為第一次存入緩存的時間(刷新頁面不變)。

下面我們給數據緩存添加一些實用的參數(上代碼)。


技術分享圖片
        protected void Page_Load(object sender, EventArgs e)
        {
            string ids="";
            Maticsoft.BLL.ScriptsBak bll = new Maticsoft.BLL.ScriptsBak();
            List<Maticsoft.Model.ScriptsBak> list = new List<Maticsoft.Model.ScriptsBak>();
            list = bll.GetAll();
            for (int i = 0; i < list.Count; i++)
            {
                ids += list[i].ScriptId.ToString()+"--";
            }
            ids = ids + "完";  //這裏的ids為從數據庫中讀取表中的id值然後用--鏈接起來的一個字符串
            if (Cache["key"] == null)
            {
                Cache.Insert("key", ids, null, DateTime.Now.AddSeconds(40), System.Web.Caching.Cache.NoSlidingExpiration);  //這裏給數據加緩存,設置緩存時間
                //"key"為緩存的鍵,ids為緩存起來的值,null為緩存依賴項,這裏沒有使用緩存依賴項,所以為null,下面會詳細介紹緩存依賴項
                   //null後面為緩存的時間為40秒
                  //最後一個參數為設置時間的格式,ASP.NET允許你設置一個絕對過期時間或滑動過期時間,但不能同時使用,
                  //我們這裏設置的為絕對過期時間,也就是沒刷新一次頁面後緩存數據為40秒,40秒後會從數據庫中重新獲取。 
                Response.Write("cache加載為---" + Cache["key"] + "</br>");
            }
            else
            {
                Response.Write("cache加載為---" + Cache["key"] + "</br>");
            }
            Response.Write("直接加載為---" + ids + "</br>");
        }
技術分享圖片

數據緩存:將一些耗費時間的條目加入到一個對象緩存集合中,以鍵值的方式存儲。我們可以通過使用Cache.Insert()方法來設置緩存的過期,優先級,依賴項等。


三、頁面緩存


 protected void Page_Load(object sender, EventArgs e)
        {
            string date = DateTime.Now.ToString();
            Response.Write(date);
        }
技術分享圖片
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="cache.WebForm1" %>
<%@ OutputCache Duration="10" VaryByParam="none" %>  
<!---添加上這一句代碼意思是,添加此頁面緩存十秒,這十秒之內,刷新頁面將讀緩存起來頁面的值,不再執行Page_Load方法。
     Page_Load方法是每十秒執行一次-->

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <div>
    
    </div>
</body>
</html>
技術分享圖片

<%@ OutputCache Duration="10" VaryByParam="none" %> 這條指令標簽為該頁面添加緩存,Duration這個參數指定頁面緩存時間為10秒,VaryByParam這個指定頁面參數,也就是這樣子的,打個比方,例如這樣一個頁面http://www.cnblogs.com/knowledgesea/admin/EditPosts.aspx?postid=2536603&update=1,那麽他的參數也就是postid和update,如果這樣頁面我們可以把指令標簽寫為<%@ OutputCache Duration="10" VaryByParam="postid;update" %> 參數與參數之間用分號隔開,這樣子也就吧每個單獨的頁面緩存起來了,他緩存的就是postid=2536603&update=1或者postid=1&update=2等等不一樣的參數頁面全部緩存起來。這裏可以使用一個簡便的方法,就是<%@ OutputCache Duration="10" VaryByParam="*" %>,緩存起來所有當前的頁面下參數不一樣的頁面。

ASP.NET不會再執行頁面的生命周期和相關代碼而是直接使用緩存的頁面,簡單點理解也就是我註釋中介紹的。


四、控件緩存


1.ObjectDataSource這樣的數據源控件,可以在屬性欄中找到相應的屬性,進行設置,下面我列出個例子,設置啟動緩存,緩存時間為10秒,時間類型為絕對時間。

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" EnableCaching="True" CacheDuration="10" CacheExpirationPolicy="Absolute"></asp:ObjectDataSource>

2.沒有緩存屬性的控件要加緩存

protected void Page_Load(object sender, EventArgs e)  
        {
            string date = DateTime.Now.ToString();
            TextBox1.Text = date;
        }
技術分享圖片
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="cache.WebForm1" %>
<%@ OutputCache Duration="10" VaryByControl="TextBox1"%>
<!--VaryByControl的參數為要緩存的控件id-->

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        </div>
    </form>
</body>
</html>
技術分享圖片

這裏的TextBox控件就加了緩存,這裏的緩存時間為10秒,也就是10秒內ASP.NET不會再執行頁面的生命周期和相關代碼而是直接使用緩存的頁面。


五、緩存依賴 (詳細:http://www.cnblogs.com/knowledgesea/p/3904929.html)


技術分享圖片
protected void Page_Load(object sender, EventArgs e)  
        {
            string str = "";
            if (Cache["key"] == null)
            {
                str = System.IO.File.ReadAllText(Server.MapPath("TextFile1.txt")); //讀取TextFile1.txt文件中的數據
                CacheDependency dp = new CacheDependency(Server.MapPath("TextFile1.txt"));//建立緩存依賴項dp
                Cache.Insert("key", str, dp);
                Response.Write(Cache["key"]);   //如果TextFile1.txt這個文件的內容不變就一直讀取緩存中的數據,一旦TextFile1.txt文件中的數據改變裏面重新讀取TextFile1.txt文件中的數據
            }
            else
            {
                Response.Write(Cache["key"]);
            }

        }
技術分享圖片

緩存依賴項使緩存依賴於其他資源,當依賴項更改時,緩存條目項將自動從緩存中移除。緩存依賴項可以是應用程序的 Cache 中的文件、目錄或與其他對象的鍵。如果文件或目錄更改,緩存就會過期。


六、配置文件中設置緩存


技術分享圖片
<system.web>
  <caching>
    <outputCacheSettings>
      <outputCacheProfiles>
     <addname="ProductItemCacheProfile" duration="60"/>
   </outputCacheProfiles>
</outputCacheSettings>
   </caching>
</system.web>
技術分享圖片 技術分享圖片
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="cache.WebForm1" %>
<%@ OutputCache CacheProfile="ProductItemCacheProfile" VaryByParam="none" %>
<!--這裏的CacheProfile參數與配置文件中的保持一至-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <div>
    
    </div>
</body>
</html>
技術分享圖片

這樣就給頁面添加了緩存為60秒的頁面。


七、緩存的回調函數


技術分享圖片
protected void Page_Load(object sender, EventArgs e)  
        {
            string str = "";
            if (Cache["key"] == null)
            {
                str = System.IO.File.ReadAllText(Server.MapPath("TextFile1.txt")); //讀取TextFile1.txt文件中的數據
                CacheDependency dp = new CacheDependency(Server.MapPath("TextFile1.txt"));//建立緩存依賴項dp
                Cache.Insert("key", str, dp, DateTime.Now.AddSeconds(20), Cache.NoSlidingExpiration, CacheItemPriority.Low, CacheItemRemovedCallback); 
                //CacheItemPriority這個參數為緩存的優先級他分好多種級別,為了防止緩存占滿時系統自己刪除緩存的優先順序廢除緩存的,後面的為回調函數的名稱。
                Response.Write(Cache["key"]);   //如果TextFile1.txt這個文件的內容不變就一直讀取緩存中的數據,一旦TextFile1.txt文件中的數據改變裏面重新讀取TextFile1.txt文件中的數據
            }
            else
            {
                Response.Write(Cache["key"]);
            }

        }

        public void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason) //這個為緩存移除時的回調函數,一定要保持與 Cache.Insert()方法中的最後一個參數名字一致,
            //這裏使用了委托,你可以在 Cache.Insert()這個函數中轉定義看到的,所以這裏的格式就只能按我寫的這種方法簽名寫。
        {
            System.IO.File.WriteAllText(Server.MapPath("log.txt"),"緩存移除原因為:"+reason.ToString());
        }
技術分享圖片

例子中的回調函數寫的是生成一個log.txt,文件記錄每一次緩存移除的原因。


八、配置文件中的緩存設置


我們服務器有開啟緩存功能, 緩存功能可以減少您訪問網站時候網站在服務器裏面的編譯時間, 大大加快您網站的訪問速度, 如果您需要對您網站進行頻繁更新的話, 您可以考慮暫時將緩存時間減少,或者暫時關閉緩存

請將下列代碼放進web.config文件裏面放在您網站的根目錄;

1.在web.config裏面設置縮小緩存的時間,請在web.config裏面用下面的定義

<system.webServer>
<caching>
<profiles>
<remove extension=".aspx" />
<add extension=".aspx" policy="CacheForTimePeriod"

kernelCachePolicy="DontCache" duration="00:00:01" varyByQueryString="*" />
</profiles>
</caching>
</system.webServer>

2. 如果要關閉某個頁面的caching功能,請在web.config裏面用下面的定義

<configuration>
<location path="showStockPrice.asp">
<system.webServer>
<caching>
<profiles>
<remove extension=".asp" />
<add extension=".asp" policy="DontCache" kernelCachePolicy="DontCache"/>
</profiles>
</caching>
</system.webServer>
</location>
</configuration>

3. 如果要關閉整個程序的caching功能,請在web.config裏面用下面的定義

<configuration>
<system.webServer>
<caching>
<profiles>
<remove extension=".asp" />
<add extension=".asp" policy="DontCache" kernelCachePolicy="DontCache"/>
</profiles>
</caching>
</system.webServer>
</configuration>

4. 如果要關閉根目錄某個或某幾個文件夾的caching功能,請在web.config裏面用下面的定義

<location path="~/folderA,~/folderB">
<system.webServer>
<caching>
<profiles>
<remove extension=".asp" />
<add extension=".asp" policy="DontCache" kernelCachePolicy="DontCache"/>
</profiles>
</caching>
</system.webServer>
</location>
</configuration>

asp.net緩存 (轉)