1 启用当前数据库的 SQL Server Service Broker
a 检查Service Broker 是否开启
SELECT is_broker_enabled FROM sys.databases WHERE name = 'WLZhuJianMes'
查询结果:is_broker_enabled de 结果是 0,代表数据库没有启动 Service Broker
解决办法:注:两句同时执行,单独执行显示:正在回滚不合法事务。估计回滚已完成: 100%。
b 开启 Service Broker
ALTER DATABASE WLZhuJianMes SET NEW_BROKER WITH ROLLBACK IMMEDIATE;
ALTER DATABASE WLZhuJianMes SET ENABLE_BROKER;
再次查询is_broker_enabled状态,状态为1,数据库没有启动 Service Broker成功
光用ALTER DATABASE DBName SET ENABLE_BROKER;语句开启经常会死机卡住,解决这个问题的方法是,先停止其它正在使用数据库的程序,然后运行
ALTER DATABASE DBName SET NEW_BROKER WITH ROLLBACK IMMEDIATE;
ALTER DATABASE DBName SET ENABLE_BROKER;
在数据库中停用 Service Broker
将数据库改为设置 DISABLE_BROKER 选项。
示例
复制
USE master ;
GO
ALTER DATABASE AdventureWorks2008R2 SET DISABLE_BROKER ;
GO
2 新建 Windows 服务程序 ,设置服务的相关信息
Code:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; namespace DamonService { public partial class Service1 : ServiceBase { static string _connStr = ConfigurationManager.AppSettings["Connection"].ToString(); public Service1() { InitializeComponent(); this.WriteLog("初始化"); this.WriteLog(_connStr); SqlDependency.Start(_connStr);//传入连接字符串,启动基于数据库的监听 // 先手动启动一次 UpdateGrid(0); } protected override void OnStart(string[] args) { this.WriteLog("服务开始启动"); } protected override void OnStop() { this.WriteLog("服务停止"); } private void UpdateGrid(int sync) { try { using (SqlConnection connection = new SqlConnection(_connStr)) { //依赖是基于某一张表的,而且查询语句只能是简单查询语句, //不能带top或 *,同时必须指定所有者,即类似[dbo].[] using (SqlCommand command = new SqlCommand(@"SELECT [Mid] ,[MatTitle] FROM [dbo].[IPGMatter] where issend=0", connection)) { command.CommandType = CommandType.Text; connection.Open(); SqlDependency dependency = new SqlDependency(command); dependency.OnChange += new OnChangeEventHandler(dependency_OnChange); SqlDataReader sdr = command.ExecuteReader(); Console.WriteLine(); while (sdr.Read()) { if (sync == 1) { // sdr. string id = sdr["MatTitle"].ToString(); this.WriteLog(id); } } sdr.Close(); } } } catch (Exception ex) { WriteLog("UpdateGrid:" + ex.StackTrace); } } #region 监听 private void dependency_OnChange(object sender, SqlNotificationEventArgs e) { SqlDependency dependency = sender as SqlDependency; dependency.OnChange -= dependency_OnChange; if (e.Info == SqlNotificationInfo.Insert) { WriteLog("UpdateGrid:" + "Insert"); UpdateGrid(1); } else if (e.Info == SqlNotificationInfo.Update) { UpdateGrid(-2); } else if (e.Info == SqlNotificationInfo.Delete) { UpdateGrid(0); } else { UpdateGrid(0); } } #endregion #region 日志 private void WriteLog(String message) { string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "serverLog.txt"); FileInfo file = new FileInfo(path); if (!file.Exists) { using (FileStream fs = File.Create(path)) { fs.Close(); } } using (FileStream fileStream = new FileStream(path, FileMode.Append, FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fileStream)) { sw.WriteLine(DateTime.Now.ToString() + ":" + message); } } } #endregion } }
安装和卸载服务的脚本
保存为bat文件,放在服务程序的根目录
C:WindowsMicrosoft.NETFramework64v4.0.30319installutil.exe /i DamonService.exe
C:WindowsMicrosoft.NETFramework64v4.0.30319installutil.exe /u DamonService.exe