asp.net 实现文件缓存依赖,数据库缓存依赖
Demo简单的是实现Asp.net2.0中缓存机制的实现:
注:对数据库的缓存依赖,.net目前并不支持oracle数据库(方法可以参考转帖文章)》
public partial class _Default : System.Web.UI.Page
{
string connstr;
protected void Page_Load(object sender, EventArgs e)
{
connstr = "server=.;dataBase=MIS;uid=sa;password=123";
}
protected void Button1_Click(object sender, EventArgs e)
{
//-------------------文件依赖缓存---------------------
DataTable dt=getInfo();
CacheDependency cd=new CacheDependency(Server.MapPath("file.txt"));
Cache.Insert("Data",dt,cd);
}
private DataTable getInfo()
{
using (SqlConnection conn = new SqlConnection(connstr))
{
string sql = "select * from mis";
SqlCommand cmd = new SqlCommand(sql,conn);
conn.Open();
SqlDataAdapter ada = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ada.Fill(dt);
return dt;
}
}
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();
}
else
{
//缓存过期
Response.Write("Cache is null");
}
}
protected void Button2_Click(object sender, EventArgs e)
{
//-------------MSSQL数据库依赖缓存--------------------
string dbname = "MIS"; //注意,数据库必须在web.config中做相应的配置
string tblname = "mis";
//启用指定数据库,数据表的缓存依赖
SqlCacheDependencyAdmin.EnableTableForNotifications(connstr, tblname);
SqlCacheDependency scd = new SqlCacheDependency(dbname,tblname);
DataTable dt = getInfo();
Cache.Insert("Data", dt, scd);
}
}
web.config:
<connectionStrings>
<add name ="mis" connectionString ="server=.;dataBase=MIS;uid=sa;password=123"/>
</connectionStrings>
<system.web>
<caching >
<sqlCacheDependency >
<databases >
<add name="MIS" connectionStringName="mis"/>
</databases>
</sqlCacheDependency>
</caching>
</system.web>
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/JustLovePro/archive/2008/11/07/3248697.aspx