使用SqlDependency进行缓存

 

缓存是每个系统都必定涉及到的功能,一般的缓存有一个难题——什么时候清除?如Asp.Net中的cache可以设置一个过期时间,但设置多久合适呢?长了浪费,短了就失去缓存的意义了。使用SqlDependency进行缓存则可以解决这个问题。

SqlDependency是.net2.0封装的一个类型,当然要配合sql2005或以上版本才能使用。

SqlDependency类需要数据库的ServiceBroker来支持,当数据库中的数据发生变化时通知应用程序更新缓存,这才是最有效的缓存方式。

步骤一:

sql数据库必须开启ServiceBroker服务,首先检测是否已经启用ServiceBroker,检测方法:

Select DATABASEpRoPERTYEX('数据库名称','IsBrokerEnabled')

--1表示已经启用0表示没有启用

步骤二:

如果ServiceBroker没有启用,使用下面语句启用:

ALTER DATABASE <数据库名称> SET ENABLE_BROKER;

步骤三:

在实现基于服务的SQL数据缓存依赖过程中,需要显式调用SqlDependency.Start来启动接受依赖项更改通知的侦听器。

SqlDependency.Start(connectionString);//推荐将这段代码加到Global.asax的Application_Start方法中
SqlDependency.Stop(connectionString);//用于关闭,可加在Global.asax的Application_End方法中

步骤四:缓存实现

 使用sqldependency实现缓存的代码:

public class CacheHelper
{
static Cache WebCache = HttpContext.Current.Cache;
static string DefaultConn = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;

public static DataTable GetSystemParams()
{
if (WebCache["SystemParam"] == null)
{
string strSQL = "select uSystemParamID,ParamName,ParamValue,Description from dbo.DTS_SystemParam";
SqlDataAdapter da
= new SqlDataAdapter(strSQL, DefaultConn);
SqlDependency dep
= new SqlDependency(da.SelectCommand);
dep.OnChange
+= new OnChangeEventHandler(dep_OnChange);
DataTable tbl
= new DataTable();
da.Fill(tbl);
WebCache[
"SystemParam"] = tbl;
return tbl;
}
else
{
return (DataTable)WebCache["SystemParam"];
}
}

private static void dep_OnChange(object sender, SqlNotificationEventArgs e)
{
WebCache.Remove(
"SystemParam");
}
}

注意:

使用 SqlDependency 订阅查询通知必须向SQL Server Service Broker提供制定规则的查询语句,一般来讲,必须是简单的sql查询语句(不能用*,不能用top,不能用函数,包括聚合函数,不能用子查询,包括where后的子查询,不能用外连接,自连接,不能用临时表,不能用变量,不能用视图,不能垮库,表名之前必须加类似dbo数据库所有者这样的前缀例如:select * from table1,select column1 from table1,select count(*) from table1 都是错误的sql查询语句,select column1 from dbo.table1 则是正确的语句。

原文地址:https://www.cnblogs.com/tuyile006/p/1660910.html