sqlCacheDependency 更新缓存Cache
第一步
修改web,config
<!--定义数据库连接-->
<connectionStrings>
<add
name="NorthwindConnectionString"
connectionString="Server=USERRYRDB;Database=Northwind;UID=sa;pwd=密码"
providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<!-- 定义缓存策略-->
<caching>
<sqlCacheDependency
enabled="true" pollTime="10000">
<databases>
<!--
name:必需的 String 属性。
要添加到配置集合中的
SqlCacheDependencyDatabase 对象的名称。
此名称用作 @ OutputCache 指令上
SqlDependency 属性的一部分。
pollTime:设置 SqlCacheDependency
轮询数据库表以查看是否发生更改的频率(以毫秒计算)。这儿是一个测试,所以设为10秒,请加大此值
-->
<add connectionStringName="NorthwindConnectionString"
name="Categories"/>
</databases>
</sqlCacheDependency>
</caching>
</system.web>
第二步.定义cachedData测试类
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;
/// <summary>
/// Summary description for CachedData
///
</summary>
public class CachedData
{
private string
Key;
private string _Source;
/// <summary>
///
指示数据从哪儿读取的
/// </summary>
public string Source { get {
return _Source; } }
public CachedData()
{
Key =
"Categories";
_Source = "未知";
}
//读取数据
public DataView getFromCache() {
if
(HttpRuntime.Cache[Key] == null)
{
//取数据
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
SqlCommand comm = new SqlCommand("SELECT [CategoryID], [CategoryName],
[Description] FROM [Categories]", conn);
SqlDataAdapter sda = new
SqlDataAdapter(comm);
DataSet ds = new DataSet();
conn.Open();
sda.Fill(ds);
DataView dv =
ds.Tables[0].DefaultView;
conn.Close();
//启用更改通知
SqlCacheDependencyAdmin.EnableNotifications(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
//连接到 SQL Server 数据库并为 SqlCacheDependency 更改通知准备数据库表
SqlCacheDependencyAdmin.EnableTableForNotifications(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString,
"Categories");
//制定缓存策略
SqlCacheDependency scd =
new SqlCacheDependency("Categories", "Categories");
//插入缓存
HttpRuntime.Cache.Insert(Key, dv, scd);
_Source = "Database";
return dv;
}
else
{
//从缓存中取值
_Source = "cache";
return (DataView)HttpRuntime.Cache[Key];
}
}
}
这样就完成了。写个页面测试一下就行了。