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

在.NET 8中使用AddStandardResilienceHandler与AddStandardHedgingHandler实现弹性

.NET8 中使用标准弹性/对冲处理器替代自定义Polly策略的实现方案

一、更新NuGet包

首先需升级Polly及相关依赖到兼容.NET8的版本,替换原有包引用:

<PackageReference Include="Polly" Version="8.2.0" /> <!-- 兼容.NET8的最新稳定版 -->
<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="8.0.0" /> <!-- .NET8标准弹性处理器核心包 -->
<PackageReference Include="Microsoft.Graph" Version="5.55.0" /> <!-- 确保Graph客户端与HttpClient兼容 -->

二、使用AddStandardResilienceHandler的实现示例

1. 在Program.cs中配置HttpClient与弹性策略

将弹性策略绑定到HttpClient,微软预定义了包含重试、熔断、超时、速率限制的最佳实践组合:

// Program.cs 服务注册段
builder.Services.AddHttpClient("GraphResilientClient")
    .AddStandardResilienceHandler(options =>
    {
        // 重试策略配置(匹配原自定义的抖动退避逻辑)
        options.Retry.MaxRetryAttempts = 5;
        options.Retry.Delay = TimeSpan.FromSeconds(1);
        options.Retry.BackoffType = DelayBackoffType.Jittered;

        // 熔断策略配置(对齐原自定义参数)
        options.CircuitBreaker.MinimumThroughput = 5; // 至少5次请求后评估熔断
        options.CircuitBreaker.FailureRatio = 1.0; // 5次全失败触发熔断
        options.CircuitBreaker.BreakDuration = TimeSpan.FromMinutes(1);

        // 自定义重试日志(替代原自定义策略的onRetry逻辑)
        options.OnRetry = args =>
        {
            var logger = args.ServiceProvider.GetRequiredService<ILogger<GraphSvcClient>>();
            logger.LogWarning(args.Exception, "调用Microsoft Graph失败,将在{Delay}后重试,第{RetryAttempt}次重试", 
                args.Delay, args.AttemptNumber);
            return ValueTask.CompletedTask;
        };
    });

// 注册配置好弹性策略的GraphServiceClient
builder.Services.AddScoped<GraphServiceClient>(sp =>
{
    var httpClient = sp.GetRequiredService<IHttpClientFactory>().CreateClient("GraphResilientClient");
    var tokenService = sp.GetRequiredService<IAzureAuthTokenService>();
    
    return new GraphServiceClient(httpClient, async requestMessage =>
    {
        var accessToken = await tokenService.GetAccessTokenAsync();
        requestMessage.Headers.Authorization = new AuthenticationHeaderValue(JwtBearerDefaults.AuthenticationScheme, accessToken);
    });
});

// 注册自定义Graph客户端服务
builder.Services.AddScoped<IGraphSvcClient, GraphSvcClient>();

2. 改造GraphSvcClient类

无需再手动创建和包裹Polly策略,直接注入配置好的GraphServiceClient:

public sealed class GraphSvcClient(GraphServiceClient graphServiceClient) : IGraphSvcClient
{
    private readonly GraphServiceClient _graphServiceClient = graphServiceClient.IsNotNull();

    /// <summary>
    /// 获取已配置弹性策略的Microsoft Graph客户端
    /// </summary>
    public Task<GraphServiceClient> GetGraphServiceClientAsync()
    {
        return Task.FromResult(_graphServiceClient);
    }

    // 示例:调用Graph API的方法,弹性策略自动生效
    public async Task<User> GetCurrentUserAsync()
    {
        return await _graphServiceClient.Me.GetAsync();
    }
}

三、使用AddStandardHedgingHandler的实现示例

对冲策略适合延迟敏感场景,会在指定延迟后发送额外请求,取第一个成功响应:

1. 在Program.cs中配置对冲处理器

builder.Services.AddHttpClient("GraphHedgingClient")
    .AddStandardHedgingHandler(options =>
    {
        // 对冲策略核心配置
        options.Hedging.MaxHedgedAttempts = 2; // 原始请求+1次对冲请求
        options.Hedging.Delay = TimeSpan.FromMilliseconds(500); // 等待500ms未响应则发送对冲请求

        // 同时配置基础弹性策略(重试、熔断等)
        options.Retry.MaxRetryAttempts = 3;
        options.CircuitBreaker.BreakDuration = TimeSpan.FromMinutes(1);
    });

// 注册使用对冲策略的GraphServiceClient
builder.Services.AddScoped<GraphServiceClient>(sp =>
{
    var httpClient = sp.GetRequiredService<IHttpClientFactory>().CreateClient("GraphHedgingClient");
    var tokenService = sp.GetRequiredService<IAzureAuthTokenService>();
    
    return new GraphServiceClient(httpClient, async requestMessage =>
    {
        var accessToken = await tokenService.GetAccessTokenAsync();
        requestMessage.Headers.Authorization = new AuthenticationHeaderValue(JwtBearerDefaults.AuthenticationScheme, accessToken);
    });
});

四、与自定义Polly策略相比的注意事项

  • 策略作用方式:自定义策略需手动包裹代码块,标准处理器绑定到HttpClient,自动应用于所有该客户端的请求,减少重复代码,避免漏加策略。
  • 预定义最佳实践:标准处理器内置了微软针对HTTP请求的最佳策略组合(含超时、速率限制),而原自定义策略仅包含重试和熔断,覆盖场景更全面。
  • 版本兼容性:必须升级Polly到8.x版本,旧版Polly(7.x)与.NET8标准处理器不兼容;同时需确保Microsoft.Graph等客户端包版本支持最新HttpClient配置。
  • 日志与监控:标准处理器默认集成.NET日志系统,无需手动编写重试/熔断日志,还支持OpenTelemetry监控弹性事件,便于排查问题。
  • 对冲策略的局限性:对冲会增加服务端负载,仅适用于读操作等幂等场景,写操作需谨慎使用,避免重复提交数据。
  • 配置灵活性:标准处理器支持通过Options完全自定义各策略参数(如重试条件、熔断阈值),可针对不同外部服务(Azure SQL、Graph)配置独立的HttpClient和策略。
  • 错误过滤逻辑:自定义策略直接捕获Exception,标准处理器默认针对HTTP可重试状态码(5xx、429)和网络异常重试,也可通过options.Retry.ShouldRetry自定义过滤规则,更贴合HTTP请求场景。

内容的提问来源于stack exchange,提问作者santosh kumar patro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 10:18:15