我将从第二个查询开始回答。首先您需要启用服务代理
SELECT [name], [service_broker_guid], [is_broker_enabled] FROM [master].[sys].[databases]
在输出检查is_broker_enabled 列是否设置为1,如果没有运行下面的查询(更改数据库名称)
ALTER DATABASE sampleNotifications SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE ;
将必要的表添加到您要监控的数据库中。在你的 webAPI 的 web.config 中添加这个数据库的连接字符串
在您的 webAPI 中安装 signalR nuget
安装包 Microsoft.AspNet.SignalR
创建一个 hubs 文件夹并添加一个 signalR hub 类,可以有基本的 onConnected 方法
public override Task OnConnected()
{
//you can log the connection ID.
return base.OnConnected();
}
在 global.asax.cs 或 startup.cs 中注册 signalR
RouteTable.Routes.MapHubs(); //for global.asax.cs and will work only for signalR 1.1. From 2.0 onwards you need to have startup class
或
app.MapSignalR(); //startup.cs
现在最重要的部分是启动 SQLDependency 类并处理更改事件。重要的部分是您需要定义您正在监视的确切内容,例如下面我在 global.asax.cs 中添加的一个简单方法来监视sampleNotifications DB的TestNotifications表
private void RegisterSQLNotifications()
{
string connectionString = ConfigurationManager.ConnectionStrings["sampleNotifications"].ConnectionString;
SqlDependency.Start(connectionString);
string commandText = @"Select * from dbo.TestNotifications";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(commandText, connection))
{
connection.Open();
var sqlDependency = new SqlDependency(command);
sqlDependency.OnChange += sqlDependency_OnChange;
// NOTE: You have to execute the command, or the notification will never fire.
using (SqlDataReader reader = command.ExecuteReader())
{
}
}
}
}
void sqlDependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Info == SqlNotificationInfo.Insert)
{
//This is how signalrHub can be accessed outside the SignalR Hub MyHub.cs file
// you can add your business logic here, like what exactly needs to be broadcasted
var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.sendNotifications();
}
//Call the RegisterSQLNotifications method again
RegisterSQLNotifications();
}
在 global.asax.cs 的 Application_Start 中调用 RegisterSQLNotifications。现在,只要您的表中有插入,就会触发 sqlDependency_OnChange 事件,您可以广播到相应的客户端
在客户端添加下面的 HTML 页面。您可以针对您的 WPF 项目进行相应修改。
var 连接 = $.hubConnection();
连接.url = "http://localhost:40471/signalr"; //API地址
var alertsHubProxy = connection.createHubProxy('MyHub')
//broadcast alert
alertsHubProxy.on('sendNotifications', function (item) {
//do something here
});
关于您的第一个查询 - 在 2 台不同的机器上运行 webAPI 和数据库应该没问题。请参阅这个使用多个 IIS 实例的横向扩展示例
http://www.asp.net/signalr/overview/performance/scaleout-with-sql-server
几个最近的链接
http://techbrij.com/database-change-notifications-asp-net-signalr-sqldependency
http://www.codeproject.com/Articles/883702/Real-Time-Notifications-using-SignalR-and-SQL-Depe
http://venkatbaggu.com/signalr-database-update-notifications-asp-net-mvc-usiing-sql-dependency/