緩存技術

1、OutputCache輸出緩存

語法:<%@ OutputCache Duration="60" VaryByParam="CategoryID"%>

Duration緩存間隔時間 單位秒

VaryByParam參數 可以爲none(無)

例:    <SelectParameters>
                <asp:QueryStringParameter Name="CategoryID" QueryStringField="CategoryID"
                    Type="Int32" DefaultValue="1" />
            </SelectParameters>
        </asp:SqlDataSource>
        <br />
        <asp:HyperLink ID="HyperLink1" runat="server" Height="20px"
            NavigateUrl="~/Default.aspx?CategoryID=1" Width="20px">1</asp:HyperLink>

用VaryByParam配合sql查詢語句使用CategoryID來篩選表格中的內容

回調緩存,是一個頁面大部分都是靜態的情況,而需要一小部分是動態的,這時候就需要回調緩存,

回調緩存需要定義一個方法在後置文件中,例:

    public static string GetHttp(HttpContext context)
    {
        return DateTime.Now.ToString();
    }

在源代碼中:

 (1) time:<%=DateTime.Now.ToString() %>

 (2)<%Response.WriteSubstitution(new HttpResponseSubstitutionCallback(GetHttp));%>

(1)中的時間在第一次訪問時,加入到OutCache的,在緩存週期時間裏,刷新不會得到新的時間,而(2)在相同頁面上調用回調緩存,每次刷新都是新的時間

另外還有一種方法叫Page Fragment Caching,它是將需要緩存的數據做成用戶自定義控件,將OutCache寫在用戶自定義控件中,把自定義控件放入一個新的頁面,在這新的頁面中不定義outCache,那麼只有自定義控件會被放到OutCache,而此頁面中其它控件都不會被放入OutCache

2、DataCache 數據緩存

數據緩存是將數據放到緩存區,在每次訪問時,如果Cache中有指定的Source那麼就將Cache中的Source邦定到GridView中,否則就新建立數據存入Cache,例如下:

        DataView Source;

        Source = (DataView)Cache["MyDataSet"];
        if(Source == null)
        {SqlConnection thisSqlConnection = new SqlConnection(@"server = localhost;Integrated Security = true;" + "Database=northwind");
            SqlDataAdapter thisDataAdapter = new SqlDataAdapter("SELECT ProductName,CategoryID FROM Products", thisSqlConnection);
            //SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisDataAdapter);
            DataSet thisSet = new DataSet();
            thisDataAdapter.Fill(thisSet, "Products");
            thisSqlConnection.Close();
            Source = new DataView(thisSet.Tables["Products"]);
            Cache["MyTables"] = Source;
        }       
        GridView1.DataSource = (object)Source;
        GridView1.DataBind();

3、SQL Cache SQL緩存

(a)打開dos 在vs目錄下會有一個aspnet_regsql.exe工具

(1)aspnet_regsql.exe -S "localhost" -E -d "Northwind" -ed                      //爲SQL緩存依賴項啓用該數據庫

(2)aspnet_regsql.exe -S "localhost" -E -d "Northwind" -et -t "Products"  //爲SQL緩存依賴項啓用該表

(b) 打開web.config

 <caching>
   <sqlCacheDependency enabled="true" pollTime="1000" >//多久檢查一次數據看是否更改

    <databases>
     <add name="Northwind" connectionStringName="NorthwindConnectionString" />//Northwind爲數據庫, 後面是數據庫連接字符串名
    </databases>
   </sqlCacheDependency>
  </caching>
(c)設置所使用該庫和表的源文件

SqlDependency="Northwind:Products“//庫和表之間用:連接

<%@ OutputCache Duration="999999" SqlDependency="Northwind:Products" VaryByParam="none" %>

也可以在數據庫控件上指定<asp:SqlDataSource EnableCaching="true" CacheDuration="Infinite" SqlCacheDependency="Northwind:Products" ... />

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章