如何在使用Azure SDK重试策略时记录Blob连接重试次数
记录Blob连接重试次数&复现重试场景
一、记录重试次数的方法
Azure Blob SDK没有直接通过BlobServiceClient暴露重试次数的属性,你可以通过以下几种方式捕获并统计重试行为:
1. 自定义重试策略跟踪计数
继承SDK的RetryPolicy,重写ShouldRetry方法,在每次触发重试时递增计数器:
public class TrackingRetryPolicy : RetryPolicy { private int _totalRetryCount = 0; // 暴露只读属性获取累计重试次数 public int TotalRetryCount => _totalRetryCount; public TrackingRetryPolicy(RetryOptions options) : base(options) { } public override bool ShouldRetry(int attemptNumber, Exception exception, out TimeSpan retryDelay) { var shouldRetry = base.ShouldRetry(attemptNumber, exception, out retryDelay); if (shouldRetry) { _totalRetryCount++; // 这里可以根据需求将日志写入文件、数据库或监控系统 Console.WriteLine($"触发第{_totalRetryCount}次重试,尝试次数:{attemptNumber},延迟:{retryDelay.TotalSeconds}秒"); } return shouldRetry; } }
使用时替换默认的重试策略:
var retryOptions = new RetryOptions { Delay = TimeSpan.FromSeconds(5), MaxRetries = 5, Mode = RetryMode.Exponential, MaxDelay = TimeSpan.FromSeconds(5), NetworkTimeout = TimeSpan.FromSeconds(5) }; var blobOptions = new BlobClientOptions(); var trackingPolicy = new TrackingRetryPolicy(retryOptions); blobOptions.RetryPolicy = trackingPolicy; BlobServiceClient blobServiceClient = new BlobServiceClient(blobConnectionString, blobOptions); // 执行Blob操作后,通过trackingPolicy.TotalRetryCount获取累计重试次数
2. 通过日志系统捕获重试信息
Azure SDK默认集成Microsoft.Extensions.Logging,可以配置日志级别为Information或Debug,捕获Azure.Core类别下的重试日志。日志条目会包含重试次数、延迟、错误原因等信息。
示例配置(.NET Core):
{ "Logging": { "LogLevel": { "Default": "Information", "Azure.Core": "Information" } } }
日志内容示例:
Azure.Core: Retry attempt 1 will be made after 5 seconds. Reason: Service request failed. Status: 503 (Service Unavailable)
你可以自定义日志处理器,解析这些日志条目来统计重试次数。
3. 订阅诊断事件跟踪重试
Azure SDK会发出Azure.Core.Retry诊断事件,通过DiagnosticListener订阅该事件即可捕获重试细节:
using System.Diagnostics; // 订阅Azure.Core的诊断事件 using var listener = new DiagnosticListener("Azure.Core"); listener.SubscribeWithAdapter(new { OnRetry = (dynamic args) => { int attemptNumber = args.AttemptNumber; // AttemptNumber从1开始,第一次重试对应AttemptNumber=2 int retryCount = attemptNumber - 1; Console.WriteLine($"当前请求已重试{retryCount}次,尝试编号:{attemptNumber}"); } });
二、复现多次重试的场景
1. 模拟网络故障或请求超时
- 使用代理工具(如Fiddler、Charles)拦截Blob服务的请求,返回5xx状态码(如500、503)或模拟请求超时,触发SDK的重试逻辑。
- 在代码中手动限制网络带宽或断开网络连接,模拟无法访问Blob服务的场景。
2. 使用无效的存储账户配置
- 修改连接字符串中的存储账户名称为不存在的名称,或使用错误的访问密钥,请求会返回403/无法连接错误,触发重试。
- 示例无效连接字符串:
string invalidConnectionString = "DefaultEndpointsProtocol=https;AccountName=invalidaccount123;AccountKey=invalidKey==;EndpointSuffix=core.windows.net";
3. 临时限制存储账户网络访问
- 在Azure门户中,进入存储账户的“网络”设置,临时设置为“拒绝所有网络访问”,此时客户端请求会被拒绝,触发重试。测试完成后恢复网络配置即可。
4. 使用故障注入工具(测试场景)
对于自动化测试,可以使用Azure SDK的故障注入扩展,在客户端配置中注入延迟、错误响应:
var blobOptions = new BlobClientOptions(); blobOptions.AddPolicy(new FaultInjectionPolicy(options => { // 模拟503错误,触发重试 options.StatusCode = HttpStatusCode.ServiceUnavailable; options.ErrorRate = 1.0; // 100%的请求触发错误 }), HttpPipelinePosition.PerCall);
内容的提问来源于stack exchange,提问作者Sanket Vaidya
相关产品推荐
相关产品推荐

