我需要记录通过APS.NET CORE 2.1+中的Polly定义的重试策略。
我的代码在下面显示了Polly retry polly并使用HttpClient。
public IServiceProvider ConfigureServices(IServiceCollection services)
{
//...
//https://github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory
Random jitterer = new Random();
services.AddHttpClient<SimpleCastClient>()
//TransientErrors:
//Network failures(System.Net.Http.HttpRequestException)
//HTTP 5XX status codes(server errors)
//HTTP 408 status code(request timeout)
.AddTransientHttpErrorPolicy(policyBuilder =>
//Exponential backoff with Randomisation
policyBuilder.WaitAndRetryAsync(10,
retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))
+ TimeSpan.FromMilliseconds(jitterer.Next(1, 100))
));
}
[ApiVersion("1")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class MyController : ControllerBase
{
ILog _logger;
private SimpleCastClient _simpleCastClient;
public MyController(ILog logger, SimpleCastClient simpleCastClient)
{
_logger = logger;
_simpleCastClient = simpleCastClient;
}
[HttpPost]
public async Task Post()
{
await _simpleCastClient.PostAsync();
}
}
public class SimpleCastClient
{
private HttpClient _client;
public SimpleCastClient(HttpClient client)
{
_client = client;
}
public async Task PostAsync()
{
string url = $"http://localhost:1111/api/v1/Mock/";
using (var content = new StringContent("data", Encoding.UTF8, "application/json"))
{
var response = await _client.PostAsync(url, content);
}
}
}
我想知道是否有比stevejgordon上更好的方法。
答案 0 :(得分:0)
由于您使用的是ASP.NET core 2.1,请考虑使用HttpClientFactory。非常适合与Polly一起使用,并具有其他好处,并且简化了日志记录。
https://github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory
答案 1 :(得分:0)
使用HttpClientFactory,您可以将Polly策略应用于预先配置的HttpClient
,并使用在该Polly策略中在DI上配置的ILogger
,其代码如下:
services.AddHttpClient<MyServiceHttpClient>(/* etc */)
.AddPolicyHandler((services, request) => HttpPolicyExtensions.HandleTransientHttpError()
.WaitAndRetryAsync(new[]
{
TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)
},
onRetry: (outcome, timespan, retryAttempt, context) =>
{
services.GetService<ILogger<MyServiceHttpClient>>()
.LogWarning("Delaying for {delay}ms, then making retry {retry}.", timespan.TotalMilliseconds, retryAttempt);
}
));