其他
Refit结合Polly访问ASP.NET Core WebAPI
前言
在.NET Core应用中访问ASP.NET Core Web API接口,常用的方式是使用IHttpClientFactory生成HttpClient实例,并通过结合Polly策略,以实现重试,熔断等机制。
在本文中,我们将介绍如何使用Refit,结合Polly访问ASP.NET Core Web API。
Refit介绍
Refit是一个类型安全的REST开源库,可通过Refit更加简单安全地访问Web API接口。首先,需要将Web API接口转换成interface:
public interface IWeatherAPI
{
[Get("/WeatherForecast")]
Task<WeatherForecast[]> Get();
}
然后,通过RestService类生成IWeatherAPI的代理实现,通过代理直接调用Web API接口:
var weatherAPI = RestService.For<IWeatherAPI>("http://localhost:5000");
var weatherForeCasts = await weatherAPI.Get();
结合Polly
1、手工执行
可以通过Policy.ExecuteAsync方法执行Web API调用代码。下列代码实现了重试机制:
var weatherAPI = RestService.For<IWeatherAPI>("http://localhost:5000");
var weatherForeCasts = await Policy
.Handle<HttpRequestException>(
ex => ex.InnerException.Message.Any())
.RetryAsync(10, async (exception, retryCount) =>
{
await Console.Out.WriteLineAsync(exception.Message);
}).ExecuteAsync(async () => await weatherAPI.Get());
2、依赖注入
更加方便的方式是使用依赖注入的方式,自动将Refit和Polly结合起来。首先,引用Nuget包:
Refit.HttpClientFactory
Microsoft.Extensions.Http.Polly
然后,修改Startup.cs,注册RefitClient,并增加了超时和重试策略:
AsyncRetryPolicy<HttpResponseMessage> retryPolicy = HttpPolicyExtensions
.HandleTransientHttpError()
.Or<TimeoutRejectedException>()
.WaitAndRetryAsync(10, _ => TimeSpan.FromMilliseconds(5000));
AsyncTimeoutPolicy<HttpResponseMessage> timeoutPolicy = Policy
.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromMilliseconds(30000));
services.AddRefitClient<IWeatherAPI>()
.ConfigureHttpClient(c => c.BaseAddress = new Uri("http://localhost:5000"))
.AddPolicyHandler(retryPolicy)
.AddPolicyHandler(timeoutPolicy);
最后,直接使用IWeatherAPI:
private readonly IWeatherAPI _weatherAPI;
public WeatherForecastController(IWeatherAPI weatherAPI)
{
_weatherAPI = weatherAPI;
}
[HttpGet]
public async Task<IEnumerable<WeatherForecast>> Get()
{
var weatherForeCasts = await _weatherAPI.Get();
return weatherForeCasts;
}
结论
我们介绍了2种Refit结合Polly访问ASP.NET Core Web API的方法。推荐使用依赖注入方式,简化Refit集成Polly的操作。
- EOF -
看完本文有收获?请转发分享给更多人
推荐关注「DotNet」,提升.Net技能
点赞和在看就是最大的支持❤️