ASP.NET緩衝學習入門—資料緩衝

來源:互聯網
上載者:User

        前面講了如何使用頁面緩衝,現在接著學習一下如何使用資料緩衝,在講資料緩衝之前還要先說一下如果在頁面中使用參數緩衝。前面講過一個緩衝設定VaryByParam="none"為無參數,我們也可以對VaryByParam進行設定,設定的參數與隨 GET 方法屬性發送的查詢字串值對應,或與使用 POST 方法發送的參數對應。將該屬性設定為多個參數時,對於每個指定參數組合,輸出緩衝都包含一個不同版本的請求文檔。可能的值包括 none、星號
(*) 以及任何有效查詢字串或 POST 參數名稱。簡單點說,就是設定成我們在頁面中使用的QueryString名稱,看個例子:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="date.aspx.cs" Inherits="date" %><%@ OutputCache Duration="60" VaryByParam="CustomerID" %><!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:GridView ID="GridView1" runat="server" BackColor="LightGoldenrodYellow"            BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None">            <FooterStyle BackColor="Tan" />            <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />            <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />            <HeaderStyle BackColor="Tan" Font-Bold="True" />            <AlternatingRowStyle BackColor="PaleGoldenrod" />        </asp:GridView>         <br />        <br />        <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/date.aspx?CustomerID=16">16</asp:HyperLink>        <asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="~/date.aspx?CustomerID=19">19</asp:HyperLink>        </div>    </form></body></html>

protected void Page_Load(object sender, EventArgs e)    {        string conn, comm, id;        if (Request.QueryString["CustomerID"] == null)        {            id = "16";        }        else        {             id = Request.QueryString["CustomerID"];        }                conn = "Server=WEB\SQLEXPRESS;Uid=moon;Pwd=1qaz2wsx;Database=store";        comm = "SELECT * FROM orders WHERE CustomerID =" + id;        SqlDataAdapter da = new SqlDataAdapter(comm, conn);        DataSet ds = new DataSet();        da.Fill(ds);        GridView1.DataSource = ds.Tables[0];        GridView1.DataBind();                Response.Write(DateTime.Now.ToString());    }

  運行後分別點擊16和19會根據這兩個關鍵字SELECT出不同的資料,這時候根據我們傳遞的兩個參數會分別建立兩個快取頁面,在每點擊一個關鍵字後請記住顯示的時間,再反覆重新整理看看時間有什麼變化!好了接下來講一下資料緩衝。

資料緩衝(Data Caching)

  在System.Web.Caching空間裡有一個類“Cache”我們可以通過這個類對資料進行緩衝。

  最簡單的緩衝方法:Cache["MyCacheString"] = "My CSDN BLOG!!!"; 通過賦值的形式建立一個緩衝,再通過賦值的形式取出緩衝:myLabel.Text = Cache["MyCacheString"].ToString();這種方法使用非常的簡單可是功能上受到了一些限制,為了更完善的訂製緩衝,應該使用Cache.Insert()方法,下面舉個例子:

頁面裡只需要放一下GridView就可以了

using System;using System.Web.Caching;using System.Data;using System.Data.SqlClient;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partial class DataCache : System.Web.UI.Page{    DataView dv;//先聲明一個資料檢視用來存放資料庫裡的資料表    protected void Page_Load(object sender, EventArgs e)    {        dv = (DataView)Cache["ds"];//從緩衝中讀取資料表        if (dv == null)//如果緩衝是空的,就建立資料庫連接,從資料庫裡讀資料        {            string conn, comm;            conn = "Server=WEB\SQLEXPRESS;Uid=moon;Pwd=1qaz2wsx;Database=store";            comm = "SELECT * FROM orders";            SqlDataAdapter da = new SqlDataAdapter(comm, conn);            DataSet ds = new DataSet();            da.Fill(ds);            dv = ds.Tables[0].DefaultView;            //下面這句是關鍵,具體參數後面介紹            Cache.Insert("ds", dv, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(3));            Databind();            Label1.Text = DateTime.Now.ToString();//參考用的時間,可有可無        }        else        {            Databind();            Response.Write("Is Cache Data!!!");//此句可有可無        }    }          protected void Databind()//自訂的資料繫結方法    {        GridView1.DataSource = dv;        GridView1.DataBind();    }}

參數說明
  Cache.Insert (String, Object, CacheDependency, DateTime, TimeSpan) 1是緩衝的名稱,2是緩衝的資料對象,3是緩衝鍵依賴項,通常為Null,4是到期時間,如果使用相對到期時間則設為NoAbsoluteExpiration,5是可調到期時間,如果參數4使用了固定到期時間,則此參數要設成NoSlidingExpiration。呵呵是不是看的有點暈啊,舉兩個具體例子說一下到期時間的問題
Cache.Insert("ds", dv, null,DateTime.Now.AddMinutes(5) , System.Web.Caching.Cache.NoSlidingExpiration);
在這個例子裡當緩衝建立後過5分鐘就到期。
Cache.Insert("ds", dv, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5));

  這個例子裡緩衝建立後,到期時間為可調,比如1:20秒建立的緩衝到期時間應該是6:20但如果在3:20有人訪問了緩衝,則到期時間將調整為8:20,以此類推……

  我們在VS2005裡建立一個測試看看使用緩衝前和使用緩衝後的效能變化吧!看到沒有,沒有緩衝前用了0.43秒而使用緩衝後只用了0.08秒效能相差5倍多啊!!!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.