Skip to content

Commit 2c721cb

Browse files
committed
Improve retry strategy
1 parent 700a2e5 commit 2c721cb

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

projects/polly/rate-limiter-http-client/Program.cs

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,18 +13,39 @@
1313
.ConfigureHttpClient((sp, client) =>
1414
{
1515
client.Timeout = TimeSpan.FromSeconds(10);
16-
}).AddResilienceHandler("concurrency-http-policy", (builder,c) =>
16+
}).AddResilienceHandler("concurrency-http-policy", (builder, c) =>
1717
{
1818
builder
1919
.AddConcurrencyLimiter(permitLimit: 100, queueLimit: 50)
2020
.AddRetry(new RetryStrategyOptions<HttpResponseMessage>
2121
{
2222
MaxRetryAttempts = 3,
23-
Delay = TimeSpan.FromSeconds(1),
23+
DelayGenerator = static args =>
24+
{
25+
var delay = args.AttemptNumber switch
26+
{
27+
0 => TimeSpan.Zero,
28+
1 => TimeSpan.FromSeconds(1),
29+
_ => TimeSpan.FromSeconds(5)
30+
};
31+
32+
// This example uses a synchronous delay generator,
33+
// but the API also supports asynchronous implementations.
34+
return new ValueTask<TimeSpan?>(delay);
35+
},
36+
OnRetry = args =>
37+
{
38+
var logger = c.ServiceProvider.GetService<ILogger>();
39+
logger.LogError("OnRetry, Attempt: {0}", args.AttemptNumber);
40+
Console.WriteLine("OnRetry, Attempt: {0}", args.AttemptNumber);
41+
42+
// Event handlers can be asynchronous; here, we return an empty ValueTask.
43+
return default;
44+
},
2445
BackoffType = DelayBackoffType.Constant
2546
}).Build();
2647
});
2748

28-
var app = builder.Build();
49+
var app = builder.Build();
2950
app.MapRazorPages();
3051
app.Run();

projects/polly/rate-limiter-http-client/README.md

Whitespace-only changes.

0 commit comments

Comments
 (0)