器:
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
ALTER TRIGGER dbo.[authors_ASPNet_SqlCacheNotification_Trigger] ON [authors]
FOR INSERT, UPDATE, DELETE AS BEGIN
SET NOCOUNT ON
EXEC dbo.ASPNet_SqlCacheUpdateChangeIdStoredProcedure N'authors'
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
从触发器可以看出,当对authors表插入,删除以及更新的时候都会执行存储过程ASPNet_SqlCacheUpdateChangeIdStoredProcedure,该存储过程会向ASPNet_SqlCacheTablesForChangeNotification表里面添加一条记录。记录如下:
tableName notificationCreated changeId
authors 2006-06-20 09:38:26.267 1
当你对authors里面的数据做任何修改changeId都会累加,其他字段不变化。
接着要在web.config里面添加一些内容就可以使用了。
首先添加数据库连接串:
<connectionStrings>
<add name ="pubsConString" connectionString="server=localhost;database=pubs;uid=sa;pwd=mypassword;"/>
</connectionStrings>
其次添加caching节:
<system.web>
<caching>
<sqlCacheDependency enabled="true">
<databases>
<add name="pubs" connectionStringName="pubsConString" pollTime="900"/>
</databases>
</sqlCacheDependency>
</caching>
</system.web>
下面是测试代码,当页面加载的时候执行如下代码:
protected void Page_Load(object sender, EventArgs e) {
if (HttpContext.Current.Cache["xxx"] == null) {
SqlCacheDependency d = new SqlCacheDependency("pubs","authors");//pubs就是databases节指定的pubs,后面是表名
HttpContext.Current.Cache.Insert("xxx", "xxx", d);
Response.Write("Create new cache value is xxx.");
}
else{
Response.Write("Load data from cache,value is "+HttpContext.Current.Cache["xxx"].ToString());
}
}
当首次打开该页面将显示:
Create new cache value is xxx.
刷新页面后显示:
Load data from cache,value is xxx
当使用查询分析器修改authors里面的数据再次刷新页面将显示:
Create new cache value is xxx.
这说明Cache正常工作了,当表authors变化Cache里面的内容会自动失效,我的应用程序也会重新创建一个Cache对象。
注意:SqlCacheDependency由两个构造函数,SqlServer2000只支持两个参数的,一个参数的支持SqlServer2005。