码迷,mamicode.com
首页 > 数据库 > 详细

SqlDependency和SqlCacheDependency缓存的用法

时间:2015-02-12 15:52:23      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:

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");
   }
}

SqlDependency和SqlCacheDependency缓存的用法

标签:

原文地址:http://www.cnblogs.com/anyben/p/4287960.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!