【问题标题】:How to notify database changes with signalR如何使用 signalR 通知数据库更改
【发布时间】:2015-07-24 13:27:39
【问题描述】:

我刚开始使用 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>

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();
        }            
    }

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);
 }
}

global.asax:

protected void Application_Start(object sender, EventArgs e)
        {
            SqlDependency.Start(Constr);
        }

当我运行 tsql update 命令时,断点首先位于dependency_OnChange,我可以看到从SendNotification 返回的新更新文本。但它没有反映在页面上。感觉就像我快到了,但缺少一些东西。

【问题讨论】:

  • 作为提示,请尝试覆盖集线器上的 OnConnectedOnDisconnectedOnReconnected 事件。放置一些断点以查看它们发生的时间和地点
  • 当您说手动停用用户时,您是如何做到的?
  • 你的app.MapSignalR(); 中有Startup.cs
  • @lzzy。是的,我做到了。我也显示了初始计数。
  • 如果您在调试时遇到断点,那么这是一个好的开始。尝试在页面上连接一个调用 JS 函数 $.connection.hub.stop(); 的按钮。 notify.client.stopClient = function () {这条线是错的,你只需要停止连接。我建议多阅读SignalR Docs

标签: c# asp.net signalr


【解决方案1】:

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();
}

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

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

This 链接对此有更详细的说明。

如果你说dependency_OnChange事件在你更新数据库后被触发,那么不要调用SendNotifications();,而是调用一个hub方法,特别是NotifyAllClients(...)

【讨论】:

  • 尝试了您的建议。但没有奏效。在页面加载时,我看到计数为 3。然后我手动运行更新命令来停用用户。页面计数应更改为 2 而无需刷新,对吗?它仍然显示 3。我已经更新了有问题的代码
  • 你能显示停用用户的代码吗?我假设您的初始计数为 3,因为您打开了 3 个客户端(浏览器),而不仅仅是因为您的数据库中的计数为 3?
  • 数据库中有 3 条记录,所有 3 条记录都处于活动状态。因此是最初的 3。然后我运行 Update Users set Active=0 where PKUserId=1
  • 再一次,Signalr 不会监视您的数据库的更改。您需要在客户端代码中启动和停止连接。您可以在数据库中保留已连接客户端的列表并在需要时广播计数,但客户端的连接和断开连接需要从客户端完成。
  • 没有用。我用更简单的示例/代码修改了我的问题。请看一下
猜你喜欢
  • 2016-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
  • 2013-10-03
  • 1970-01-01
相关资源
最近更新 更多