ASP.NET緩存 之 Web服務器緩存

1.替換緩存

  可以使用substitution動態更新緩存頁

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


aspx

  Cached Time:<%=DateTime.Now.ToString() %>
    <br />Page Time:
        <asp:Substitution ID="Substitution1" runat="server" MethodName="GetTime" />


最後在頁面開啓緩存輸出

結果:Page Time每次都不相同,cached Time每5秒更新一次

Tips:關閉緩存輸出

this.Response.Cache.SetNoServerCaching();

2.數據依賴

   依賴於數據庫的頁面,與其相應的sql語句關聯,設置此緩存的方法:

<%@ Outputcache duration="5" varybyparam="none" SqlDependency="CommandNotification" %>


一旦頁面在緩存中,如果使用DML對數據源進行操作,她會發送通知給依賴的服務器,當服務器接到通知後,就會從緩存中移除原始查詢頁面.

如果頁面中有數據源不需要緩存,可以繞過SqlDependency,對需要的查詢語句使用AddCacheDependency代碼如下:

 using (SqlConnection conn = new SqlConnection(connectionString))
        {
            string sql = @"SELECT U.UserId,
	                            U.UserName,
	                            D.BorrowDate,
	                            D.BorrowMoney,
	                            D.RevertDate,
	                            D.IsRevert
                            FROM dbo.UserInfo AS U
                            INNER JOIN dbo.Debt AS D
	                            ON U.UserId = D.UserId";
            conn.Open();
            SqlCommand sqlCmd = new SqlCommand(sql,conn);
            SqlCacheDependency dep = new SqlCacheDependency(sqlCmd);


            GridView1.DataSource = sqlCmd.ExecuteReader();
            GridView1.DataBind();
            this.Response.AddCacheDependency(dep);
            
        }

注意此時我們還需要在Global.asax文件中添加如下代碼:

    void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup
        System.Data.SqlClient.SqlDependency.Start(ConfigurationManager.AppSettings["DebtDB"].ToString());

    }
    
    void Application_End(object sender, EventArgs e) 
    {
        //  Code that runs on application shutdown
        System.Data.SqlClient.SqlDependency.Stop(ConfigurationManager.AppSettings["DebtDB"].ToString());
    }
        

結果:執行當前頁面請求時候,生成的頁面放到輸出緩存,如果使用DML對數據源做了更新,刪除,插入操作,後臺程

<%@ OutputCache Duration="10" VaryByParam="None" VaryByCustom="userId" %>


序會收到一個通知,

從緩存中移除該頁面,刷新頁面,會看到最新的信息

3.使用varyByCustom對頁進行緩存

我下面的代碼使用查詢字符串進行頁緩存的,你可以使用Cookie,瀏覽器類型進行緩存.

  <div>
    cache time:<%=DateTime.Now.ToString() %>
    userId:
    <%=userId %>
    <br />

        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    </div>


查詢字符串:userId

 

<%@ OutputCache Duration="10" VaryByParam="None" VaryByCustom="userId" %>


 

    protected string userId;
    public readonly string connectionString = ConfigurationManager.AppSettings["DebtDB"].ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["userId"] != null)
        {
             userId = Request.QueryString["userId"].ToString();
        }

        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            string sql = @"
                            SELECT U.UserId,
	                            U.UserName,
	                            D.BorrowDate,
	                            D.BorrowMoney,
	                            D.RevertDate,
	                            D.IsRevert
                            FROM dbo.UserInfo AS U
                            INNER JOIN dbo.Debt AS D
	                            ON U.UserId = D.UserId
                                WHERE D.UserId =" + userId;
            conn.Open();
            SqlCommand sqlCmd = new SqlCommand(sql, conn);
            GridView1.DataSource = sqlCmd.ExecuteReader();
            GridView1.DataBind();

        }
    }


注意我們需要在Global.asax

重寫GetVaryByCustomString

如果不重寫就不能保證根據UserId查詢過濾出來對應的信息進行緩存。

例如我第一次 查詢UserId:1的相關信息,然後再點擊Userid:2的相關信息,居然一模一樣,只有等待緩存過期纔會顯示對應userid:2的信息

 

    public override string GetVaryByCustomString(HttpContext context, string custom)
    {
        if (custom == "userId")
        {
            return context.Request.QueryString["userId"].ToString();
        }
        return base.GetVaryByCustomString(context, custom);
    }


 

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