如何使用signalR通知数据库更改

Qwe*_*rty 3 c# asp.net signalr

我刚开始使用SignalR,想尝试实时通知.目标是在网页上继续显示更新的消息.有一个数据库表 - DummyData带有一列Message.此表只有一条记录 - Hello 当页面加载时,显示"Hello".

然后我在sql server 2012中手动运行该命令

update DummyData set Message='hello world',但邮件未在网页中更新.

ASPX:

<script>
    $(function () {
        var notify = $.connection.notificationsHub;

        $.connection.hub.start().done(function () {
            notify.server.notifyAllClients();
        });

        notify.client.displayNotification = function (msg) {               
            $("#newData").html(msg);
        };

        notify.client.stopClient = function () {
            $.connection.hub.stop();
        };
    });
</script>
 <span id="newData"></span>
Run Code Online (Sandbox Code Playgroud)

aspx.cs:

public string SendNotifications()
    {
      string message = string.Empty;
      using (SqlConnection connection = new SqlConnection(conStr))
       {
        string query = "SELECT [Message] FROM [dbo].[DummyData]";

        SqlCommand command = new SqlCommand(query, connection)
        command.Notification = null;
        SqlDependency dependency = new SqlDependency(command);
                dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();

        if (reader.HasRows)
        {
         reader.Read();
         message = reader[0].ToString();
        }
       }            
        return message;
    }

    private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            SendNotifications();
        }            
    }
Run Code Online (Sandbox Code Playgroud)

NotificationsHub.cs

public class NotificationsHub : Hub
{
 Messages obj = new Messages();
 public void NotifyAllClients(string msg)
  {
   IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>();
   context.Clients.All.displayNotification(msg);
  }

 public override System.Threading.Tasks.Task OnConnected()
  {
   NotifyAllClients();
   return base.OnConnected();
  }

 public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
 {
  NotifyAllClients();
  return base.OnDisconnected(stopCalled);
 }
}
Run Code Online (Sandbox Code Playgroud)

Global.asax中:

protected void Application_Start(object sender, EventArgs e)
        {
            SqlDependency.Start(Constr);
        }
Run Code Online (Sandbox Code Playgroud)

当我运行tsql update命令时,首先点击断点dependency_OnChange,我可以看到从中返回的新更新文本SendNotification.但它没有在页面上反映出来.感觉就像我几乎在那里,但缺少一些东西.

cds*_*sln 6

Signalr没有在数据库中查看更改.因此,当您在数据库中将用户设置为非活动状态时,它对Signalr没有任何意义.您的3个客户仍然连接.

要获得所需的结果,请将此类内容添加到您的Hub中

public override OnConnected()
{
  // Increase the active user count in the db 
  IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ServerHub>();
  Clients.All.broadcastCount(DB.GetCount());
  return base.OnConnected();
}

public override OnDisconnected() 
{
    //Decrease the connected user count in the db
  IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ServerHub>();
  Clients.All.broadcastCount(DB.GetCount());
  return base.OnDisconnected();
}
Run Code Online (Sandbox Code Playgroud)

然后,当您连接和断开客户端时,集线器将通知已连接的客户端.

您将需要以SignalR将捕获的方式断开连接,因此您不能只更改数据库中的标志.尝试$.connection.hub.stop();从您的客户打电话.

这个链接详细介绍了它.

如果您说dependency_OnChange在数据库中更新后触发了事件,那么请不要调用SendNotifications();,而是调用hub方法NotifyAllClients(...)