asp.net如何使用数据缓存

使用数据缓存

学习使用页面缓存的心得,本实例使用的sql2005数据库,如使用sql2000时做法有所不同。实现的效果是:对查询进行缓存,直到数据库中相关数据改变或页面缓存过期(分钟过期一次)。

首先在项目的“Global.asax”文件“Session_start”事件中进行监听

void Session_Start(object sender, EventArgs e)

{

    // Code that runs when a new session is started

    //开始监听数据库

System.Data.SqlClient.SqlDependency.Start(ConfigurationManager.ConnectionStrings["mytest_str"].ConnectionString);

}

页面文件代码:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        Data Cache Test<br />

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

        </asp:GridView>

    </div>

    </form>

</body>

</html>

CS文件代码:

using System;

using System.Data;

using System.Configuration;

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;

using System.Data.SqlClient;

using System.Data.Sql;

using System.Web.Caching;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        string conStr = ConfigurationManager.ConnectionStrings["mytest_str"].ConnectionString;

        SqlConnection conn = new SqlConnection(conStr);

        SqlCommand cmd = new SqlCommand("select * from jg_fund", conn);

        //cmd创建sql依赖

        SqlCacheDependency sqldepandendy = new SqlCacheDependency(cmd);

        conn.Open();

        SqlDataAdapter da = new SqlDataAdapter(cmd);

        DataSet ds=new DataSet();

        da.Fill(ds);

        da.Dispose();

        this.GridView1.DataSource = ds;

        this.GridView1.DataBind();

        conn.Close();

        //使页面缓存和sql缓存相关联,当数据库数据变化时页面缓存过期。当然也可不使用页面缓存,只用数据缓存。

        Response.AddCacheDependency(sqldepandendy);

        /*设置页面缓存*/

        Response.Cache.SetValidUntilExpires(true);//指定ASP.NET 缓存是否应忽略由使缓存无效的客户端发送的HTTP Cache-Control 标头。

        Response.Cache.SetExpires(DateTime.Now.AddMinutes(5));

        Response.Cache.SetCacheability(HttpCacheability.Public);

        /*

         *注:

         *   1Response.Cache.SetValidUntilExpires(true);指定ASP.NET 缓存是否应忽略由使缓存无效的客户端发送的HTTP Cache-Control 标头。

         *   当使用了高级<%@ OutputCache - %> 页指令时,SetValidUntilExpires 方法将被自动设置为true

         *   之所以提供此方法,是因为某些浏览器在刷新页视图时会将HTTP 缓存无效标头发送到Web 服务器并从缓存中收回该页。

         *   validUntilExpires 参数为true 时,ASP.NET 会忽略缓存无效标头,而该页将保留在缓存中直到过期为止。

         *   2Response.Cache.SetCacheability(HttpCacheability.Public);Cache-Control 标头设置为HttpCacheability 值之一。

         *   3)实现的效果是:对查询进行缓存,直到数据库中相关数据改变或页面缓存过期(分钟过期一次)。

         */

    }

}

posted on 2008-09-03 14:00  张皓  阅读(1010)  评论(0编辑  收藏  举报

导航