SqlDependency和SqlCacheDependency缓存的用法


SqlDependency配合ServiceBroker实现缓存

步骤一:

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

Select  DATABASEpRoPERTYEX('dbname','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");
   }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM