当监听的指定数据库内容某张表变化时就更新缓存
先来配置数据库,启动监听服务(SQL2008下)
执行如下语句:
ALTER DATABASE OumindBlog SET NEW_BROKER WITH ROLLBACK IMMEDIATE; ALTER DATABASE OumindBlog SET ENABLE_BROKER;
OumindBlog为数据库名称
检测数据库是否开启监听:
SELECT is_broker_enabled FROM sys.databases WHERE name = 'OumindBlog'
结果为0则是未启动,为1是启动状态
接着配置webconfig,关键代码如下:
<connectionStrings> <add name="SqlConnection" connectionString="Data Source=MATRUE-PC;Initial Catalog=OumindBlog;User Id=sa;Password=" providerName="System.Data.SqlClient"></add> </connectionStrings> <system.web> <caching> <sqlCacheDependency enabled="true" pollTime="6000"> <databases> <add name="OumindBlog" connectionStringName="SqlConnection"></add> </databases> </sqlCacheDependency> </caching>
接着启动服务:
void Application_Start(object sender, EventArgs e) { // 在应用程序启动时运行的代码 string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString; SqlDependency.Start(conStr); //启动监听服务,只需启动一次 System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(conStr);//设置通知的数据库连接,ps:只需设置一次 System.Web.Caching.SqlCacheDependencyAdmin.EnableTableForNotifications(conStr, "dbo.BlogUser");//设置通知的数据库连接和表,ps:只需设置一次 }
因为只需要启动一次,所以我放到了Global.asax文件的Application_Start下
页面调用:
string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString; string CaCheKey = "cachekey"; object objModel = CaCheHelp.GetCaChe(CaCheKey); //根据缓存索引键读取缓存对象 if (objModel == null) { string sql = "select * from BlogUser"; SqlConnection con = new SqlConnection(conStr); SqlCommand cmd = new SqlCommand(sql, con); SqlDataAdapter adapter = new SqlDataAdapter(cmd); System.Data.DataSet ds = new System.Data.DataSet(); adapter.Fill(ds, "cache"); System.Web.Caching.SqlCacheDependency cds = new System.Web.Caching.SqlCacheDependency("OumindBlog", "dbo.BlogUser");//建立关联 CaCheHelp.SetCaChe(CaCheKey, ds, cds); objModel = CaCheHelp.GetCaChe(CaCheKey); } lable_time.InnerText = ((System.Data.DataSet)objModel).Tables[0].Rows.Count.ToString();
参考:
http://kb.cnblogs.com/page/69727/ 用这个方法我数据库配置不成功,紧接着找到了下面的解决方法:http://www.csharpwin.com/dotnetspace/13325r7020.shtml
数据库启动缓存监听时报错“请为此数据库启用 Service Broker” 可以参考这个:http://www.cnblogs.com/wanghk/archive/2012/05/12/2497170.html