"可能由于暂时性失败引发了异常。如果您在连接到 SQL Azure 数据库,请考虑使用 SqlAzureExecutionStrategy。"问题的处理办法

Web API接口访问量突然剧增,Entity Framework框架提示错误“可能由于暂时性失败引发了异常。如果您在连接到 SQL Azure 数据库,请考虑使用 SqlAzureExecutionStrategy。”,错误堆栈如下:

--- 引发异常的上一位置中堆栈跟踪的末尾 ---
   在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   在 System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesInternalAsync>d__31.MoveNext()
--- 引发异常的上一位置中堆栈跟踪的末尾 ---
   在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   在 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

数据无法保存,可是重试几次保存数据又是成功的。记录一下排查问题的经过:

1、Entity Framework代码的问题

可是是并发锁引起的问题,保存数据增加线程锁。傍晚访问人数比较少,基本上没有提示错误,等到晚一点又提示错误。这个调整失败。

查询接口与提交接口在相同控制器,迁移查询API到另外控制器,一夜无事。可是第二天,访问量上来之后,有提示错误。这个调整失败。

2、数据库密码的问题

在csdn找到一篇文字,修改数据库用户名,文章链接。对于该错误,此方案完全无用。

3、dba查看数据库

数据库日志、操作系统日志正常,SQL Server数据库运行正常。dba干掉了订阅业务(数据同步业务),做了定时备份。对于该错误,dba也帮不上忙。不懂为什么dba没有想到查看数据库锁表问题。

4、数据库锁表

这是一个很大的突破,开始接近问题真相了。使用SQL Server Profiler工具,查看锁表情况,入下图所示:

观察到错误及其类似语句:

Parallel query worker thread was involved in a deadlock

锁表语句:

(@0 int,@1 nvarchar(32),@2 datetime2(7),@3 nvarchar(64),@4 int,@5 int,@6 bit)
insert [dbo].[CommandRequests](
   [CommandId]
 , [DeviceId]
 , [StartDateTime]
 , [EndDateTime]
 , [Parameters]
 , [Caller]
 , [Result]
 , [Priority]
 , [Timeout]
 , [ParentRequestId]
 , [IsSuccessful]
 , [Host])
  values (@0, @1, @2, null, null, @3, null, @4, @5, null, @6, null)

  select [CommandRequestId]
  from [dbo].[CommandRequests]
  where @@ROWCOUNT &gt; 0 and [CommandRequestId] = scope_identity()   

Stack Overflow找到一个同样的问题,有个回复真是救人于水火之中呀!摘录如下:

“I think the reason is CommandRequestId is not the primary key. If you set it as primary key you will not get dead lock. I had the same issue and when I set the Identity column as primary key it worked fine.”

最后看到就是ID主键的问题,id是自增的,但是没有设置主键。在迁移服务到云上忘记设置了,忘记设置了.......

排查超过36个小时的问题,终于搞定了!感谢那些乱分享的同行,也感谢Stack Overflow.

 

posted @ 2022-04-14 17:27  panliuwen  阅读(1552)  评论(0编辑  收藏  举报