using EntrustSettle.Common;
using EntrustSettle.Common.Http.HttpPolly;
using EntrustSettle.Model;
using Microsoft.Extensions.DependencyInjection;
using RestSharp;
using System;
namespace EntrustSettle.Extensions
{
///
///
///
public static class HttpClientSetup
{
public static void AddHttpClientSetup(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
// Http请求方式1:使用RestSharp
services.AddKeyedSingleton(HttpEnum.Hyd, new RestClient(AppSettings.app("Apis", "Hyd", "BaseUrl")));
// Http请求方式2:使用HttpClientFactory
//services.AddHttpClient(HttpEnum.Hyd.ToString(), c =>
//{
// c.BaseAddress = new Uri(AppSettings.app("Apis", "Hyd", "BaseUrl"));
//});
//services.AddSingleton();
//#region 方式2可配合Polly策略
//var retryPolicy = HttpPolicyExtensions
//.HandleTransientHttpError()
//.Or() // 若超时则抛出此异常
//.WaitAndRetryAsync(new[]
//{
// TimeSpan.FromSeconds(1),
// TimeSpan.FromSeconds(5),
// TimeSpan.FromSeconds(10)
//});
//// 为每个重试定义超时策略
//var timeoutPolicy = Policy.TimeoutAsync(10);
//services.AddHttpClient(HttpEnum.Common.ToString(), c =>
//{
// c.DefaultRequestHeaders.Add("Accept", "application/json");
//})
//.AddPolicyHandler(retryPolicy)
//// 将超时策略放在重试策略之内,每次重试会应用此超时策略
//.AddPolicyHandler(timeoutPolicy);
//services.AddHttpClient(HttpEnum.LocalHost.ToString(), c =>
//{
// c.BaseAddress = new Uri("http://www.localhost.com");
// c.DefaultRequestHeaders.Add("Accept", "application/json");
//})
//.AddPolicyHandler(retryPolicy)
//// 将超时策略放在重试策略之内,每次重试会应用此超时策略
//.AddPolicyHandler(timeoutPolicy);
//#endregion
}
}
}