大约一天后,Service Broker消息开始挂起

时间:2013-07-11 18:15:15

标签: sql-server service-broker sqldependency query-notifications

我有一个使用Service Broker的应用程序是SQL 2008.大约每天一次,数据库的性能开始受到显着影响,我已经确定这是因为Service Broker。如果我使用以下命令硬重置所有代理连接:

ALTER DATABASE [RegencyEnterprise] SET OFFLINE WITH ROLLBACK IMMEDIATE
ALTER DATABASE [RegencyEnterprise] SET ONLINE

然后表演恢复正常,直到第二天。我还注意到,当性能不佳时,运行以下查询会返回大量(当前大约1000个)处于STARTED_OUTBOUND状态的会话:

SELECT * FROM sys.conversation_endpoints

此外,以下查询不会返回其中的任何条目:

SELECT * FROM sys.dm_qn_subscriptions
SELECT * FROM sys.transmission_queue

在此查询返回的内容很多的情况下,性能似乎没问题。有问题的唯一时间是有STARTED_OUTBOUND的连接停留在此状态。

我在SQL Server 2008实例上对Service Broker所做的唯一配置是运行以下命令:

ALTER DATABASE RegencyEnterprise SET ENABLE_BROKER

通过SQL错误日志,我发现此条目也超过1000次:

07/11/2013 01:00:02,spid27s,Unknown,The query notification dialog on conversation handle '{6DFE46F5-25E9-E211-8DC8-00221994D6E9}.' closed due to the following error: '<?xml version="1.0"?><Error xmlns="http://schemas.microsoft.com/SQL/ServiceBroker/Error"><Code>-8490</Code><Description>Cannot find the remote service &apos;SqlQueryNotificationService-cb4e7a77-58f3-4f93-95c1-261954d3385a&apos; because it does not exist.</Description></Error>'.

我也在整个日志中看到这个错误十几次,但我相信我只需在数据库中创建一个主密钥就可以解决这个问题:

06/26/2013 14:25:01,spid116,Unknown,Service Broker needs to access the master key in the database '<Database name>'. Error code:26. The master key has to exist and the service master key encryption is required.

我认为这些错误的数量可能与留在队列中的会话数量有关。这是我用来订阅查询通知的C#代码:

private void EstablishSqlConnection(
    String storedProcedureName,
    IEnumerable<SqlParameter> parameters,
    Action sqlQueryOperation,
    String serviceCallName,
    Int32 timeout,
    params MultipleResult[] results)
{
    SqlConnection storeConnection = (SqlConnection) ((EntityConnection) ObjectContext.Connection).StoreConnection;
    try
    {
        using (SqlCommand command = storeConnection.CreateCommand())
        {
            command.Connection = storeConnection;
            storeConnection.Open();

            SqlParameter[] sqlParameters = parameters.ToArray();
            command.CommandText = storedProcedureName;
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.AddRange(sqlParameters);

            if (sqlQueryOperation != null)
            {
                // Register a sql dependency with the SQL query.
                SqlDependency sqlDependency = new SqlDependency(command, null, timeout);
                sqlDependency.OnChange += OnSqlDependencyNotification;
            }

            using (DbDataReader reader = command.ExecuteReader())
            {
                results.ForEach(result => result.MapResults(this, reader));
            }
        }
    }
    finally
    {
        storeConnection.Close();
    }
}

以下是我处理通知的方式:

    public static void OnSqlDependencyNotification(object sender, SqlNotificationEventArgs e)
    {
        if (e.Info == SqlNotificationInfo.Invalid)
        {
            // If we failed to register the SqlDependency, log an error
            <Error is loged here...>

            // If we get here, we are not in a valid state to requeue the sqldependency. However,
            // we are on an async thread and should NOT throw an exception. Instead we just return
            // here, as we have already logged the error to the database. 
            return;
        }

        // If we are able to find and remove the listener, invoke the query operation to re-run the query.
        <Handle notification here...>
    }

有谁知道什么会导致经纪人的关系进入这种状态?或者我可以使用哪些工具来试图找出造成这种情况的原因?我目前只有一个注册到其通知的Web服务器,因此我的方案并不过分复杂。

更新:

好的,所以我从this post确定错误“无法找到远程服务......因为它不存在”是由于SqlDependency没有正确清理它。在服务结束后,代理仍在尝试向我的应用程序发送通知。所以现在,听起来我只需要找到一种方法来清除我的应用程序启动之前没有正确清理的任何内容,然后再调用SqlDependency.Start(),但除了我的原始方法之外我还没有找到办法做到这一点上面,它使数据库脱机,是不可接受的。有谁知道要清理它吗?

3 个答案:

答案 0 :(得分:4)

我找到了解决此问题的可接受方法。首先,我将我的代码从SqlDependency迁移出来,现在我正在使用SqlNotificationRequest。这样做可以防止在意外时间创建/销毁Broker队列和服务。

即便如此,当我的应用程序退出时,仍有一些会话未被标记为已关闭,因为设置通知的原始端点不再存在。因此,每次我的服务器重新初始化我的代码时,我都会清除现有的会话。

这种调整减少了我每天在1000以上的连接次数,并且不得不手动杀死它们,最多不超过20次。我高度建议使用SqlNotificationRequest而不是SqlDependency。

答案 1 :(得分:2)

我找到了一种方法来清除卡住的对话。我检索仍然存在的所有生成的SqlDependency队列,并迭代不属于任何这些对话的对话并结束这些对话。以下是代码:

SET NOCOUNT OFF;
DECLARE @handle UniqueIdentifier
DECLARE @count INT = 0

-- Retrieve orphaned conversation handles that belong to auto-generated SqlDependency queues and iterate over each of them
DECLARE handleCursor CURSOR
FOR 
SELECT [conversation_handle]
FROM sys.conversation_endpoints WITH(NOLOCK)
WHERE
    far_service COLLATE SQL_Latin1_General_CP1_CI_AS like 'SqlQueryNotificationService-%' COLLATE SQL_Latin1_General_CP1_CI_AS AND
    far_service COLLATE SQL_Latin1_General_CP1_CI_AS NOT IN (SELECT name COLLATE SQL_Latin1_General_CP1_CI_AS FROM sys.service_queues)

DECLARE @Rows INT
SELECT @Rows = COUNT(*) FROM sys.conversation_endpoints WITH(NOLOCK)
WHERE
    far_service COLLATE SQL_Latin1_General_CP1_CI_AS like 'SqlQueryNotificationService-%' COLLATE SQL_Latin1_General_CP1_CI_AS AND
    far_service COLLATE SQL_Latin1_General_CP1_CI_AS NOT IN (SELECT name COLLATE SQL_Latin1_General_CP1_CI_AS FROM sys.service_queues)

WHILE @ROWS>0
BEGIN
    OPEN handleCursor

    FETCH NEXT FROM handleCursor 
    INTO @handle

    BEGIN TRANSACTION

    WHILE @@FETCH_STATUS = 0
    BEGIN

        -- End the conversation and clean up any remaining references to it
        END CONVERSATION @handle WITH CLEANUP

        -- Move to the next item
        FETCH NEXT FROM handleCursor INTO @handle
        SET @count= @count+1
    END

    COMMIT TRANSACTION
    print @count

    CLOSE handleCursor;

    IF @count > 100000
    BEGIN
        BREAK;
    END

    SELECT @Rows = COUNT(*) FROM sys.conversation_endpoints WITH(NOLOCK)
    WHERE
        far_service COLLATE SQL_Latin1_General_CP1_CI_AS like 'SqlQueryNotificationService-%' COLLATE SQL_Latin1_General_CP1_CI_AS AND
        far_service COLLATE SQL_Latin1_General_CP1_CI_AS NOT IN (SELECT name COLLATE SQL_Latin1_General_CP1_CI_AS FROM sys.service_queues)
END
DEALLOCATE handleCursor;

答案 2 :(得分:0)

已启动出站表示“SQL Server已为此对话处理了BEGIN CONVERSATION,但尚未发送任何消息。” (来自联机丛书) 看起来您正在创建未被使用的对话,因此它们永远不会被关闭。

不完全确定为什么会导致性能下降。