SignalR在单个数据库更改上发送多个请求

时间:2019-06-03 07:47:17

标签: sql-server asp.net-mvc signalr

我使用SignalR创建了一个简单的通知,但现在遇到了问题。我不知道这是否正常,因为这是我第一次在项目中使用SignalR。问题是,一旦数据库发生更改,网络将发送多个请求。

这是我的代码:

Global.asax

string connString = ConfigurationManager.ConnectionStrings
    ["spms_notif"].ConnectionString;
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        // SQL Dependecy starts here
        SqlDependency.Start(connString);
    }
    protected void Application_End()
    {
        //Stop SQL dependency
        SqlDependency.Stop(connString);
    }

Signal R集线器

NotificationHub

 [HubMethodName("sendNotification")]
    public static void SendNotification()
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
        context.Clients.All.updateNotification();
    }

我的班级

NotificationRepository

public IEnumerable<NotificationModel> GetAllMessages()
    {
        var notif = new List<NotificationModel>();
        using (var connection = new SqlConnection(_connString))
        {
            connection.Open();
            using (var command = new SqlCommand(@"SELECT id, eid, description, IsRead FROM dbo.spms_tbl_notification WHERE IsRead = 0 and ActionCode = 1 and eid = "+Account.UserInfo.eid+" ORDER BY AlwaysOnTop DESC", connection))
            {
                command.Notification = null;

                var dependency = new SqlDependency(command);
                dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                if (connection.State == ConnectionState.Closed)
                    connection.Open();

                var reader = command.ExecuteReader();

                while (reader.Read())
                {
                    NotificationModel value = new NotificationModel();
                    value.id = Convert.ToString(reader.GetValue(0));
                    value.eid = Convert.ToString(reader.GetValue(1));
                    value.description = Convert.ToString(reader.GetValue(2));
                    notif.Add(value);
                }
            }
        }
        return notif;
    }

private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            NotificationHub.SendNotification();
        }
    }

在我的客户端

<script>
$(function () {
    // Declare a proxy to reference the hub.
    var notifications = $.connection.notificationHub;

    //debugger;
    // Create a function that the hub can call to broadcast messages.
    notifications.client.updateNotification = function () {
        getAllMessages()

    };
    // Start the connection.
    $.connection.hub.start().done(function () {
        //alert("connection started")
        getAllMessages();
    }).fail(function (e) {
        alert(e);
    });
});

function getAllMessages() {
    var tbl = $('#messagesTable');
    $.ajax({
        url: '@Url.Action("Get", "Notification")',
        contentType: 'application/html ; charset:utf-8',
        type: 'GET',
        dataType: 'json'
    }).success(function (result) {
        $("#notif_body").html("");
        console.log('length: ' + result.length);
        $('.count_notif').html(result.length);
        $.each(result, function (i, v) {
            $("#notif_body").append('<li>' +
                    '<a href="#">' +
                        '' + v.description + '' +
                    '</a>' +
                '</li>');
        });
        console.log("DATA CAPTURED");
    }).error(function () {
        console.log("ERROR CAPTURING DATA");
    });
}

</script>

SqlDependecy中使用的表

The Table used in SqlDependecy

多重请求

The multiple request

0 个答案:

没有答案