博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
.NET 4.0 MemoryCache with SqlChangeMonitor
阅读量:7126 次
发布时间:2019-06-28

本文共 3725 字,大约阅读时间需要 12 分钟。

Summary

There isn't a lot of documentation on the internet about how to use the SqlChangeMonitor with the new MemoryCache class in .NET 4.0, so I thought I would add my example:

Database Preparation

The first step is to prepare your database for SqlChangeMonitor. This feature uses the SQL Server Service Broker to setup a notification event that fires to notify when data changes that would change the returned recordset of a query, so we have to enable the service broker on our database:

ALTER DATABASE database_name SET TRUSTWORTHY ON WITH ROLLBACK IMMEDIATE ALTER DATABASE database_name SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE ALTER AUTHORIZATION ON DATABASE::database_name TO sa

With that out of the way, we can continue on to setting up the cache in code…

Code 

public bool IsInMaintenanceMode(){ bool inMaintenanceMode; if (MemoryCache.Default["MaintenanceMode"] == null) { CacheItemPolicy policy = new CacheItemPolicy(); string connStr = "MY CONNECTION STRING"; SqlDependency.Start(connStr); using (SqlConnection conn = new SqlConnection(connStr)) { using (SqlCommand command = new SqlCommand( "Select MaintenanceMode From dbo.MaintenanceMode", conn)) { command.Notification = null; SqlDependency dep = new SqlDependency(); dep.AddCommandDependency(command); conn.Open(); inMaintenanceMode = (bool)command.ExecuteScalar(); SqlChangeMonitor monitor = new SqlChangeMonitor(dep); policy.ChangeMonitors.Add(monitor); } } MemoryCache.Default.Add("MaintenanceMode", inMaintenanceMode, policy); } else { inMaintenanceMode = (bool)MemoryCache.Default.Get("MaintenanceMode"); } return inMaintenanceMode; }

This code is a simple way to cache a value that specifies whether the application is currently in maintenance mode. The dbo.Maintenance table contains a single row with a single bit column. This code will allow your application to continuously check to see if it should go into maintenance mode, without hammering your database. 

When the value changes in the database, the application receives a notification that it should invalidate the cache. Then, in the next call to IsInMaintenanceMode, MemoryCache.Default["MaintenanceMode"] returns null, causing it to re-register the notification. Just what we want.

Notes 

  • You must call SqlDependency.Start first, otherwise it just doesn't work.
  • Your SQL Command must follow the guidelines located at . There are lots of things to consider about how you build your query, so pay close attention to this document.
  • After adding your command object to the SqlDependency object, you must execute the command at least once, otherwise it will not register the notification.
  • After executing the command once, you can dispose of your connection. Behind the scenes, .NET will keep a connection open to your SQL Server to listen for the notification.

I hope this helps some people out. I know I spent way too much time looking for documentation that just didn't exist.

Edits

 

  • I have attached a sample project illustrating the use of the code above. It is a simple Console application that just shows how you might use this. Run the SQL script in the attached code to create a database, then run the application. Once it is running, change the value of "MaintenanceMode" in the table. You will see when it is hitting the database, and when it is using the cache. I hope this provides a better example of usage.

翻译:  需要先对数据库执行 命令

 

ALTER DATABASE database_name SET TRUSTWORTHY ON WITH ROLLBACK IMMEDIATE ALTER DATABASE database_name SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE ALTER AUTHORIZATION ON DATABASE::database_name TO sa 再就是sql语句的要求 "列名必须写出来(不能用*),不能用top,不能用函数,包括聚合函数,不能用子查询,包括where后的子查询,不能用外连接,自连接,不能用临时表,不能用变量,不能用视图,不能垮库,而且表名之前必须加类似dbo这样的前缀" 很多限制

转载地址:http://jceel.baihongyu.com/

你可能感兴趣的文章
neutron-metadata-proxy无响应,导致windos2003密码透传失败
查看>>
用Python实现用户登录接口
查看>>
毕业前1个月的想法
查看>>
例程详析动态链接库
查看>>
geopy使用详解
查看>>
Notebook Workflows: The Easiest Way to Implement Apache Spark Pipelines
查看>>
mysql必知必会表样例
查看>>
我的友情链接
查看>>
python logging 模块在windows报错ConfigParser.NoSectionError: No section
查看>>
windows下python3虚拟环境搭建
查看>>
error at ::0 formal unbound in pointcut
查看>>
关于linux下Squid透明代理的试验
查看>>
马哥2016全新Linux+Python高端运维班第四期-第三次作业
查看>>
AngularJS基础语法
查看>>
程序编译过程
查看>>
《Linux学习并不难》归档和压缩(2):tar包的使用和管理
查看>>
cookie与session详解
查看>>
一键 安装lamp+lnmp+ftp+Tomcat任意选择5分钟起飞
查看>>
我的友情链接
查看>>
K-Backup的网络备份与集中存储介绍
查看>>