执行 DbCommand 失败,因为超时已过期 .net 核心

Sha*_*ani 7 c# sql-server azure entity-framework-core .net-core

我的目标是提供简单的 API 来从Payments包含 5 列的(~400 行)表中检索数据。

Payment: Id (int),
PaymentsNumber (tinyint),
Rate (decimal(18,2)),
ProductType (tinyint),
ClientClubType (tinyint).
Run Code Online (Sandbox Code Playgroud)

用户可以使用请求参数(应返回约 12 行)来发出帖子请求:

PaymentsRequest 
{
    public int? PaymentsNumber { get; set; }
    public byte? ProductType { get; set; }
    public byte? ClientClubType { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

使用 EF 核心:

services.AddDbContext<MyContext>(cfg => cfg.UseSqlServer(Configuration.GetConnectionString(...),optionsBuilder => optionsBuilder.CommandTimeout(60)));

public async Task<IEnumerable<Payments>> GetPaymentsAsync(PaymentsRequest request)
{
    IQueryable<Payments> query = this._context.Set<Payments>();
    query = query.Where(filter => 
                        (request.ClientClubType == null || filter.ClientClubType == request.ClientClubType) &&
                        (request.ProductType == null || filter.ProductType == request.ProductType) &&
                        (request.PaymentsNumber == null || filter.PaymentsNumber == request.PaymentsNumber));

    return await query.ToListAsync();
}
Run Code Online (Sandbox Code Playgroud)

在 azure 应用程序洞察中,我可以看到 2 个连续的日志,由相同的异常引起:

  1. Log1:执行 DbCommand 失败。
  2. Log2:执行超时已过期。操作完成前超时时间已过或服务器未响应。

Log1 是(虽然这里不需要写 log2):

执行 DbCommand 失败(65,238 毫秒)[Parameters=[@__request_ClientClubType_0='?' (Size = 1) (DbType = Byte), @__request_ProductType_1='?' (Size = 1) (DbType = Byte)], CommandType='Text', CommandTimeout='60']

SELECT [p].[Id], [p].[ClientClubType], [p].[PaymentsNumber], [p].[ProductType], [p].[Rate] FROM [Payments] AS [p] WHERE ( ([p].[ClientClubType] = @__request_ClientClubType_0) AND @__request_ClientClubType_0 不是 NULL) AND (([p].[ProductType] = @__request_ProductType_1) AND @__request_ProductType_1 不是 NULL)

我的应用程序是部署在 azure linux webapp 上的 .net core 3.0 应用程序。

该问题仅在生产中出现,并非每次都发生,我无法从 MSSMS 重建该问题。任何的想法?

更新:

在@panagiotis-kanavos 发表评论后,我将代码更新为:

services.AddDbContextPool<MyContext>(cfg => cfg.UseSqlServer(Configuration.GetConnectionString(...),optionsBuilder => optionsBuilder.CommandTimeout(60)));

public async Task<IEnumerable<Payments>> GetPaymentsAsync(PaymentsRequest request)
{
    IQueryable<Payments> query = this._context.Payments;
    query = query.Where(filter => 
                        (filter.ClientClubType == request.ClientClubType) &&
                        (filter.ProductType == request.ProductType) &&
                        (filter.PaymentsNumber == request.PaymentsNumber));

    return await query.ToListAsync();
}
Run Code Online (Sandbox Code Playgroud)

小智 2

  • 您的超时时间为 60 秒,可以增加。这样做通常不是一个好主意,因为它会隐藏其他问题。
  • 如果表有大量写入,或者某些事务有长时间运行,它可能会阻塞/与您的查询竞争。
  • 如果您的查询是 SQL 操作的较大开始事务 - 结束事务序列的一部分,则它可能会被其他打开的事务阻塞
  • 与上一个相同 - 如果同时/几乎同时对此查询进行多次调用,则可能会减慢每个查询的处理速度。我见过这样的情况:Web 前端填充了 20 行数据的屏幕,其中每一行都是对同一类型数据的同一 Web-API 端点的不同调用。例如,获取过去 12 个月每个月的每月交易金额总额。