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

如何通过Azure Application Insights实现Azure Redis的端到端事务跟踪?

我来帮你梳理下在这个场景下实现Azure Redis端到端事务跟踪的具体步骤,结合你已经在用的Application Insights和现有代码来展开:

1. 先确保Redis客户端与Application Insights的依赖跟踪集成

首先,你需要让Application Insights自动捕获Redis的操作请求。如果用的是Microsoft.Extensions.Caching.StackExchangeRedis(也就是你代码里_redisCache对应的常用封装),可以通过以下配置开启自动跟踪:

  • 安装必要的NuGet包:确保你已经安装了Microsoft.ApplicationInsights.DependencyCollector,这个包负责收集各类依赖调用(包括Redis)。
  • 在appsettings.json里启用Redis依赖跟踪:
"ApplicationInsights": {
  "InstrumentationKey": "你的应用洞察密钥",
  "DependencyTracking": {
    "EnableRedisDependencyTracking": true
  }
}
  • 在Startup的ConfigureServices里配置App Insights时,确保依赖收集器被启用(默认是开启的,但可以显式声明):
services.AddApplicationInsightsTelemetry();
services.AddDependencyTrackingTelemetryModule();
2. 在你的缓存操作代码中添加自定义跟踪细节

自动跟踪能捕获基本的Redis调用,但你可能需要更细粒度的信息(比如缓存命中/未命中、键名、过期时间等)。可以在你的SearchIngredientAsync方法里扩展跟踪逻辑:

private readonly IDistributedCache _redisCache;
private readonly ILogger<YourService> _logger;
private readonly TelemetryClient _telemetryClient;

// 构造函数注入TelemetryClient
public YourService(IDistributedCache redisCache, ILogger<YourService> logger, TelemetryClient telemetryClient)
{
    _redisCache = redisCache;
    _logger = logger;
    _telemetryClient = telemetryClient;
}

public async Task<IReadOnlyCollection<FoodDescriptionModel>> SearchIngredientAsync(string name)
{
    var cacheKey = "FoodDescriptionModelCollection";
    // 启动一个Redis操作的跟踪上下文,关联到当前请求
    using var getOperation = _telemetryClient.StartOperation<DependencyTelemetry>("Redis Get", cacheKey);
    
    try
    {
        bool cacheHit = _redisCache.TryGetValue(cacheKey, out IReadOnlyCollection<FoodDescriptionModel> cached);
        
        // 给跟踪事件添加自定义属性,方便后续筛选分析
        getOperation.Telemetry.Properties["CacheHit"] = cacheHit.ToString();
        getOperation.Telemetry.Properties["TargetKey"] = cacheKey;
        
        if (cacheHit)
        {
            _logger.LogInformation("缓存命中,键: {CacheKey}", cacheKey);
            _telemetryClient.TrackTrace($"Redis缓存命中: {cacheKey}", SeverityLevel.Information);
            return cached.Where(x => x.LongDescription.Contains(name)).ToList() as IReadOnlyCollection<FoodDescriptionModel>;
        }
        else
        {
            _logger.LogWarning("缓存未命中,键: {CacheKey}", cacheKey);
            _telemetryClient.TrackTrace($"Redis缓存未命中: {cacheKey}", SeverityLevel.Warning);
            
            // 从数据源加载数据(这里替换成你实际的加载逻辑)
            var data = await LoadFoodDescriptionsFromDataSourceAsync();
            
            // 跟踪Redis写入操作
            using var setOperation = _telemetryClient.StartOperation<DependencyTelemetry>("Redis Set", cacheKey);
            try
            {
                await _redisCache.SetAsync(cacheKey, data, new DistributedCacheEntryOptions 
                { 
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(1) 
                });
                
                setOperation.Telemetry.Properties["ExpirationDays"] = "1";
                setOperation.Telemetry.Properties["TargetKey"] = cacheKey;
                setOperation.Telemetry.Success = true;
            }
            catch (Exception ex)
            {
                setOperation.Telemetry.Success = false;
                setOperation.Telemetry.Exception = ex;
                _telemetryClient.TrackException(ex);
                throw;
            }
            
            return data.Where(x => x.LongDescription.Contains(name)).ToList() as IReadOnlyCollection<FoodDescriptionModel>;
        }
    }
    catch (Exception ex)
    {
        getOperation.Telemetry.Success = false;
        getOperation.Telemetry.Exception = ex;
        _telemetryClient.TrackException(ex);
        throw;
    }
}
3. 验证端到端跟踪的效果

配置和代码调整完成后,你可以在Azure Portal的Application Insights里查看完整的事务链:

  • 打开Transaction Search,找到你的SearchIngredientAsync对应的请求,点击进去就能看到关联的Redis依赖调用(包括Get和Set操作)。
  • 在Application Map里,你能直观看到请求从API到Redis的流转路径,以及每个节点的性能和错误情况。
  • 利用Logs查询,你可以筛选Redis相关的跟踪事件,比如用这个Kusto查询:
dependencies
| where type == "Redis"
| where name startswith "Redis "
| project timestamp, name, properties.TargetKey, properties.CacheHit, success, duration
4. 处理复杂Redis事务的跟踪(如果后续需要)

如果之后你用到Redis的批量操作或事务(比如MULTI/EXEC),可以手动创建一个自定义的依赖跟踪,把整个事务作为一个单独的依赖项记录,同时在属性里记录事务内的所有操作细节,确保端到端的链路完整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:11:26