Azure SQL频繁连接超时

时间:2016-03-17 09:31:13

标签: sql-server entity-framework azure

我们在Azure上运行一个Web应用程序(2个实例),由SQL Azure数据库提供支持。在任何给定时间,有50-150名用户使用该网站。数据库以S2性能级别运行。 DTU平均约为20%。

然而,每天有几次我突然在日志中出现数百个错误,超时,如下:

  

执行命令定义时发生错误。有关详细信息,请参阅内部异常。

     

等待操作超时。

     

超时已过期。操作完成之前经过的超时时间或服务器没有响应。尝试连接到路由目标时发生此故障。尝试连接到原始服务器时花费的持续时间是 - [Pre-Login] initialization = 1;握手= 21; [登录]初始化= 0;认证= 0; [登录后]完成= 1;

我们使用EF6进行默认命令超时的查询。我已经配置了这个执行策略:

SetExecutionStrategy("System.Data.SqlClient", 
            () => new SqlAzureExecutionStrategy(10, TimeSpan.FromSeconds(15)));

数据库(总共大约15GB)被严格索引。这些错误发生在整个地方,通常在1-2分钟内就会发生几十到几百个。

我可以采取哪些措施来防止这种情况发生?

1 个答案:

答案 0 :(得分:8)

它在1-2分钟内发生的事实可能意味着活动爆发或某些可能锁定表格的过程。

如果您在此期间的DTU为20%不是CPU问题,但您始终可以通过在DB上运行此查询找到哪些瓶颈:

SELECT TOP 10 
total_worker_time/execution_count AS Avg_CPU_Time
        ,execution_count
        ,total_elapsed_time/execution_count as AVG_Run_Time
        ,(SELECT
              SUBSTRING(text,statement_start_offset/2,(CASE
                                                           WHEN statement_end_offset = -1 THEN LEN(CONVERT(nvarchar(max), text)) * 2 
                                                           ELSE statement_end_offset 
                                                       END -statement_start_offset)/2
                       ) FROM sys.dm_exec_sql_text(sql_handle)
         ) AS query_text 
FROM sys.dm_exec_query_stats 
ORDER BY Avg_CPU_Time DESC

即使数据库被大量索引,索引也会碎片化,我建议运行它来检查当前的碎片:

select a.*,b.AverageFragmentation from 
(               SELECT tbl.name AS [Table_Name], tbl.object_id, i.name AS [Name], i.index_id, CAST(CASE i.index_id WHEN 1 THEN 1 ELSE 0 END AS bit) AS [IsClustered], 
CAST(case when i.type=3 then 1 else 0 end AS bit) AS [IsXmlIndex], CAST(case when i.type=4 then 1 else 0 end AS bit) AS [IsSpatialIndex]
               FROM
               sys.tables AS tbl
               INNER JOIN sys.indexes AS i ON (i.index_id > 0 and i.is_hypothetical = 0) AND (i.object_id=tbl.object_id))a
inner join
(               SELECT tbl.object_id, i.index_id, fi.avg_fragmentation_in_percent AS [AverageFragmentation]
               FROM
               sys.tables AS tbl
               INNER JOIN sys.indexes AS i ON (i.index_id > 0 and i.is_hypothetical = 0) AND (i.object_id=tbl.object_id)
               INNER JOIN sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED') AS fi ON fi.object_id=CAST(i.object_id AS int) AND fi.index_id=CAST(i.index_id AS int)
)b
on a.object_id=b.object_id and a.index_id=b.index_id
order by AverageFragmentation desc

您还可以使用Azure自动化计划自动重建碎片索引,请参阅以下答案:Why my Azure SQL Database indexes are still fragmented?