You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8 Azure Service Bus后台服务如何在Application Insights查看平均响应时间

如何在Application Insights中查看Azure Service Bus消息处理后台服务的平均响应时间

我基于.NET 8.0开发了一款负责接收Azure Service Bus队列消息的后台服务,已在Program.cs中完成Application Insights配置(相关代码如下)。目前在Application Insights的Performance板块仅能看到API调用及发布者应用的响应时间,请问是否可以查看该后台服务的平均响应时间?

// 后台服务的Program.cs    
services.AddApplicationInsightsTelemetryWorkerService(new ApplicationInsightsServiceOptions
{
    ConnectionString = "InstrumentationKey=...",
    EnableAdaptiveSampling = false
});

// ReceiptsBackgroundService.cs
public async Task Handle(Message message, CancellationToken cancellationToken)
{
    using (IServiceScope scope = _serviceScopeFactory.CreateScope())
    {
        var scopedProcessingService = scope.ServiceProvider
            .GetRequiredService<IReceiptsScopedProcessingService>();

        await scopedProcessingService.DoWorkAsync(message, cancellationToken);
    }

    await _queueClient.CompleteAsync(message.SystemProperties.LockToken)
        .ConfigureAwait(false);
}

// ReceiptsScopedProcessingService.cs
public async Task DoWorkAsync(Message message, CancellationToken stoppingToken)
{
    // 执行业务处理
    
    _logger.Log(LogLevel.Information, "处理成功。", "处理成功。");
}

在Application Insights的Performance板块中,我仅能看到发布者应用的性能数据。

Application Insights中的Performance板块


解决方案

可以通过以下方式让Application Insights捕获后台服务处理消息的性能数据,进而查看平均响应时间:

1. 手动创建自定义操作跟踪

由于后台服务的消息处理不属于自动跟踪的Web请求范畴,需要手动标记处理流程的生命周期:

修改ReceiptsBackgroundService.cs,注入TelemetryClient并创建操作:

private readonly TelemetryClient _telemetryClient;

// 构造函数注入TelemetryClient
public ReceiptsBackgroundService(IServiceScopeFactory serviceScopeFactory, IQueueClient queueClient, TelemetryClient telemetryClient)
{
    _serviceScopeFactory = serviceScopeFactory;
    _queueClient = queueClient;
    _telemetryClient = telemetryClient;
}

public async Task Handle(Message message, CancellationToken cancellationToken)
{
    // 创建自定义操作,覆盖从接收消息到完成确认的全流程
    using var operation = _telemetryClient.StartOperation<RequestTelemetry>("ServiceBus消息处理");
    operation.Telemetry.Properties["消息ID"] = message.MessageId;
    operation.Telemetry.Properties["队列名称"] = _queueClient.QueueName;

    try
    {
        using (IServiceScope scope = _serviceScopeFactory.CreateScope())
        {
            var scopedProcessingService = scope.ServiceProvider
                .GetRequiredService<IReceiptsScopedProcessingService>();

            await scopedProcessingService.DoWorkAsync(message, cancellationToken);
        }

        await _queueClient.CompleteAsync(message.SystemProperties.LockToken)
            .ConfigureAwait(false);
        
        operation.Telemetry.Success = true;
    }
    catch (Exception ex)
    {
        operation.Telemetry.Success = false;
        _telemetryClient.TrackException(ex);
        throw;
    }
}

2. 启用Service Bus自动跟踪(推荐)

通过安装对应扩展包,让Application Insights自动捕获Service Bus消息处理的性能数据:

  • 安装必要的NuGet包:
Install-Package Azure.Messaging.ServiceBus
Install-Package Microsoft.ApplicationInsights.WorkerService
  • 在Program.cs中配置自动跟踪:
services.AddApplicationInsightsTelemetryWorkerService(options =>
{
    options.ConnectionString = "InstrumentationKey=...";
    options.EnableAdaptiveSampling = false;
});

// 启用Service Bus操作的自动跟踪
services.AddServiceBus()
    .AddApplicationInsightsTelemetry();

如果使用旧版Microsoft.Azure.ServiceBus,可通过配置启用跟踪:

services.AddSingleton(new ServiceBusTelemetryOptions
{
    EnableTelemetry = true
});

3. 在Application Insights中查看数据

配置完成后等待数分钟让数据上报,进入Performance板块:

  • 在「操作名称」筛选器中选择自定义的ServiceBus消息处理(或自动生成的Service Bus操作名称)
  • 即可查看该操作的平均响应时间、调用次数、失败率等核心指标

内容的提问来源于stack exchange,提问作者Sohlae

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 23:48:27