【问题标题】:Is there any way to react on Azure SQL Database changes?有什么方法可以对 Azure SQL 数据库更改做出反应?
【发布时间】:2019-03-25 12:52:35
【问题描述】:

我在我的应用程序中使用 SignalR 并响应我使用 Sql Dependency 的数据库更改

SqlDependency.Start(con);

但我收到以下错误:

此版本的 SQL Server 不支持语句“RECEIVE MSG”

据我了解,Azure SQL 数据库不支持 Service Broker。

除了迁移到 Azure VM 之外,还有什么解决方案吗?

具有 SQL 依赖关系的代码示例:

public class NotificationComponent
{
    public void RegisterNotification(DateTime currentTime)
    {
        string conStr = ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;
        string sqlCommand = @"SELECT [ContactID],[ContactName],[ContactNo] from [dbo].[Contacts] where [AddedOn] > @AddedOn";
        using (SqlConnection con = new SqlConnection(conStr))
        {
            SqlCommand cmd = new SqlCommand(sqlCommand, con);
            cmd.Parameters.AddWithValue("@AddedOn", currentTime);
            if (con.State != System.Data.ConnectionState.Open)
            {
                con.Open();
            }
            cmd.Notification = null;
            SqlDependency sqlDep = new SqlDependency(cmd);
            sqlDep.OnChange += sqlDep_OnChange;
            using (SqlDataReader reader = cmd.ExecuteReader())
            {

            }
        }
    }

    void sqlDep_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            SqlDependency sqlDep = sender as SqlDependency;
            sqlDep.OnChange -= sqlDep_OnChange;

            var notificationHub = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
            notificationHub.Clients.All.notify("added");
            RegisterNotification(DateTime.Now);
        }
    }

    public List<Contact> GetContacts(DateTime afterDate)
    {
        using (MyPushNotificationEntities dc = new MyPushNotificationEntities())
        {
            return dc.Contacts.Where(a => a.AddedOn > afterDate).OrderByDescending(a => a.AddedOn).ToList();
        }
    }
}

【问题讨论】:

  • 是什么导致了您想要响应的数据库更改? (即,你能向上移动因果链吗。)
  • 您是在谈论数据更改(插入/删除/更新记录)还是架构更改?
  • @AlbertoMorillo 关于插入/删除/更新
  • 您的最终解决方案是什么?我不认为数据库驱动的方法适合今天的事件驱动架构。我希望您需要设置事件机制并订阅特定事件。

标签: c# asp.net azure signalr azure-sql-database


【解决方案1】:

您可以使用 Azure Logic App 中的 SQL 的“创建项目时”和“修改项目时”触发器来响应数据更改。

Azure 逻辑应用中的 SQL 连接器使用轮询机制使用 TIMESTAMP / ROWVERSION 列查询表的更改。这种数据类型是专门为 SQL 中的这种处理而设计的。轮询查询实质上选择所有行版本大于最后轮询值的行。该行为是可靠的,因为该列由 SQL Server 控制,并且在没有新数据的情况下性能非常快。当有新数据时,性能堪比简单的行查询。

更多信息请阅读this文章。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-22
    • 2019-09-14
    • 2018-12-23
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 2017-12-05
    • 2021-09-26
    相关资源
    最近更新 更多