Asp.net2.0中缓存机制的实现
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.Web.Caching;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
string connstr;
protected void Page_Load(object sender, EventArgs e)
{
this.Label1.Text = "";
connstr = "server=.;dataBase=test;uid=hmhm;password=hmhm";
}
private DataTable getInfo()
{
using (SqlConnection conn = new SqlConnection(connstr))
{
string sql = "select * from A";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataAdapter ada = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ada.Fill(dt);
return dt;
}
//Response.Write("来自数据库");
Label1.Text = "来自数据库";
}
private void FileDEpendency1()
{
DataTable dt = getInfo();
//文件的改变可以使用
CacheDependency cd = new CacheDependency(Server.MapPath("TextFile.txt"));
Cache.Insert("Data", dt, cd);
}
private void SqlDependency()
{
string dbname = "test"; //注意,数据库必须在web.config中做相应的配置
string tblname = "A";
//启用指定数据库,数据表的缓存依赖
SqlCacheDependencyAdmin.EnableTableForNotifications(connstr, tblname);
SqlCacheDependency scd = new SqlCacheDependency(dbname, tblname);
DataTable dt = getInfo();
Cache.Insert("Data", dt, scd);
}
protected void Button1_Click(object sender, EventArgs e)
{
//-------------------文件依赖缓存---------------------
FileDEpendency1();
}
protected void Button2_Click(object sender, EventArgs e)
{
//-------------MSSQL数据库依赖缓存--------------------
SqlDependency();
}
protected void Button3_Click(object sender, EventArgs e)
{
//-------------显示数据-----------
if (Cache.Get("Data") != null)
{
DataTable dt = Cache.Get("Data") as DataTable;
GridView1.DataSource = dt;
GridView1.DataBind();
Label1.Text = "来自缓存";
}
else
{
//缓存过期
Label1.Text = "缓存过期";
}
}
}
web.config:
<connectionStrings>
<add name ="testconnection" connectionString ="server=.;dataBase=test;uid=hm;password=123456"/>
</connectionStrings>
<system.web>
<caching >
<sqlCacheDependency >
<databases >
<add name="test" connectionStringName="testconnection"/>
</databases>
</sqlCacheDependency>
</caching>
</system.web>
下载地址: http://download.csdn.net/detail/sgear/3982004