网站建设有那些软件,天元建设集团有限公司鹿腾,seo外包公司报价,没有公司做网站前言在.NET Core应用中访问ASP.NET Core Web API接口#xff0c;常用的方式是使用IHttpClientFactory生成HttpClient实例#xff0c;并通过结合Polly策略#xff0c;以实现重试#xff0c;熔断等机制。在本文中#xff0c;我们将介绍如何使用Refit#xff0c;结合Polly访… 前言在.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)]TaskWeatherForecast[] Get();
}然后通过RestService类生成IWeatherAPI的代理实现通过代理直接调用Web API接口:var weatherAPI RestService.ForIWeatherAPI(http://localhost:5000);var weatherForeCasts await weatherAPI.Get();结合Polly1.手工执行可以通过Policy.ExecuteAsync方法执行Web API调用代码。下列代码实现了重试机制var weatherAPI RestService.ForIWeatherAPI(http://localhost:5000);var weatherForeCasts await Policy.HandleHttpRequestException(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并增加了超时和重试策略AsyncRetryPolicyHttpResponseMessage retryPolicy HttpPolicyExtensions.HandleTransientHttpError().OrTimeoutRejectedException() .WaitAndRetryAsync(10, _ TimeSpan.FromMilliseconds(5000));AsyncTimeoutPolicyHttpResponseMessage timeoutPolicy Policy.TimeoutAsyncHttpResponseMessage(TimeSpan.FromMilliseconds(30000));services.AddRefitClientIWeatherAPI().ConfigureHttpClient(c c.BaseAddress new Uri(http://localhost:5000)).AddPolicyHandler(retryPolicy).AddPolicyHandler(timeoutPolicy);最后直接使用IWeatherAPIprivate readonly IWeatherAPI _weatherAPI;public WeatherForecastController(IWeatherAPI weatherAPI)
{_weatherAPI weatherAPI;
}[HttpGet]
public async TaskIEnumerableWeatherForecast Get()
{var weatherForeCasts await _weatherAPI.Get();return weatherForeCasts;
}结论今天我们介绍了2种Refit结合Polly访问ASP.NET Core Web API的方法。推荐使用依赖注入方式简化Refit集成Polly的操作。如果你觉得这篇文章对你有所启发请关注我的个人公众号”My IO“