Sql server 大约一天后,ServiceBroker消息开始挂起

Sql server 大约一天后,ServiceBroker消息开始挂起,sql-server,service-broker,sqldependency,query-notifications,Sql Server,Service Broker,Sqldependency,Query Notifications,我有一个使用ServiceBroker的应用程序是SQL2008。每天大约有一次数据库的性能开始受到明显的影响,我已经确定这是因为ServiceBroker。如果我使用以下命令硬重置所有代理连接: ALTER DATABASE [RegencyEnterprise] SET OFFLINE WITH ROLLBACK IMMEDIATE ALTER DATABASE [RegencyEnterprise] SET ONLINE 然后性能恢复正常,直到第二天左右。我还注意到,当性能不佳时,运行以

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

ALTER DATABASE [RegencyEnterprise] SET OFFLINE WITH ROLLBACK IMMEDIATE
ALTER DATABASE [RegencyEnterprise] SET ONLINE
然后性能恢复正常,直到第二天左右。我还注意到,当性能不佳时,运行以下查询会返回大量(目前约1000个)处于STARTED_OUBOUND状态的对话:

SELECT * FROM sys.conversation_endpoints
此外,以下查询不会返回其中的任何条目:

SELECT * FROM sys.dm_qn_subscriptions
SELECT * FROM sys.transmission_queue
当此查询返回大量项时,性能似乎正常。出现问题的唯一时间是启动的连接或出站的连接停留在此状态

我对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.
06/26/2013 14:25:01,spid116,未知,Service Broker需要访问数据库“”中的主密钥。错误代码:26。主密钥必须存在,并且需要服务主密钥加密。
我认为这些错误的数量可能与被困在队列中的对话数量有关。下面是我用来订阅查询通知的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();
    }
}
专用连接(
字符串存储过程名称,
IEnumerable参数,
操作sqlQueryOperation,
字符串serviceCallName,
Int32超时,
参数MultipleResult[]结果)
{
SqlConnection storeConnection=(SqlConnection)((EntityConnection)ObjectContext.Connection).storeConnection;
尝试
{
使用(SqlCommand=storeConnection.CreateCommand())
{
command.Connection=storeConnection;
storeConnection.Open();
SqlParameter[]sqlParameters=parameters.ToArray();
command.CommandText=storedProcedureName;
command.CommandType=CommandType.storedProcess;
command.Parameters.AddRange(sqlParameters);
if(sqlQueryOperation!=null)
{
//在sql查询中注册sql依赖项。
SqlDependency SqlDependency=新的SqlDependency(命令,null,超时);
sqlDependency.OnChange+=onsqldependency通知;
}
使用(DbDataReader=command.ExecuteReader())
{
results.ForEach(result=>result.MapResults(this,reader));
}
}
}
最后
{
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...>
    }
公共静态无效OnSqlDependencyNotification(对象发送方,SqlNotificationEventArgs e)
{
if(e.Info==SqlNotificationInfo.Invalid)
{
//如果注册SqlDependency失败,请记录一个错误
//如果我们到了这里,我们将无法在有效状态下重新获得sqldependency。但是,
//我们在一个异步线程上,不应该抛出异常,而是返回
//在这里,我们已经将错误记录到数据库中。
返回;
}
//如果能够找到并删除侦听器,请调用查询操作以重新运行查询。
}
有人知道什么会导致代理的连接处于这种状态吗?或者我可以用什么工具来找出造成这种情况的原因?我目前只有一个web服务器正在注册其通知,所以我的场景并不太复杂

更新:


好的,我已经确定错误“找不到远程服务…因为它不存在”是由于SqlDependency本身没有正确清理。代理仍在尝试在服务结束后向我的应用程序发送通知。所以现在,听起来我只需要找到一种方法,在调用SqlDependency.Start()之前,在我的应用程序启动时,清除任何未正确清理的内容,但除了上面的原始方法之外,我还没有找到其他方法,该方法使数据库离线,这是不可接受的。有人知道如何清理此信息吗?

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


不过,我不完全清楚这会导致性能下降的原因。

我找到了一种方法来清除那些被卡住的对话。我检索所有生成的仍然存在的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;

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

然而,即使这样,当我的应用程序退出时,仍有一些对话没有标记为关闭,因为设置通知的原始端点已不在那里。因此,每次我的服务器重新初始化我的代码时,我都会清除现有的对话

这一调整将我每天的连接数从1000多个减少到了20个左右,我不得不手动杀死它们。我强烈建议使用