小编aub*_*urg的帖子

使用 Polly 重试 HttpClient 请求的正确方法

我有一个 Azure 函数,可以对 webapi 端点进行 http 调用。我正在关注此示例GitHub Polly RetryPolicy,因此我的代码具有类似的结构。所以在 Startup.cs 中我有:

builder.Services.AddPollyPolicies(config); // extension methods setting up Polly retry policies
builder.Services.AddHttpClient("MySender", client =>
{
    client.BaseAddress = config.SenderUrl;
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
});
Run Code Online (Sandbox Code Playgroud)

我的重试策略如下所示:

public static class PollyRegistryExtensions
{
    public static IPolicyRegistry<string> AddBasicRetryPolicy(this IPolicyRegistry<string> policyRegistry, IMyConfig config)
    {
        var retryPolicy = Policy
            .Handle<Exception>()
            .OrResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
            .WaitAndRetryAsync(config.ServiceRetryAttempts, retryCount => TimeSpan.FromMilliseconds(config.ServiceRetryBackOffMilliSeconds), (result, timeSpan, retryCount, context) =>
            {
                if (!context.TryGetLogger(out var logger)) return;

                logger.LogWarning(
                    $"Service delivery attempt {retryCount} failed, next attempt in {timeSpan.TotalMilliseconds} …
Run Code Online (Sandbox Code Playgroud)

c# .net-core polly azure-functions

3
推荐指数
1
解决办法
3万
查看次数

标签 统计

.net-core ×1

azure-functions ×1

c# ×1

polly ×1