You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
2.3 KiB
C#

9 months ago
using EntrustSettle.Common;
using EntrustSettle.Common.Http.HttpPolly;
using EntrustSettle.Model;
using Microsoft.Extensions.DependencyInjection;
9 months ago
using RestSharp;
using System;
namespace EntrustSettle.Extensions
{
/// <summary>
9 months ago
///
/// </summary>
9 months ago
public static class HttpClientSetup
{
9 months ago
public static void AddHttpClientSetup(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
9 months ago
// Http请求方式1使用RestSharp
services.AddKeyedSingleton<IRestClient>(HttpEnum.Hyd, new RestClient(AppSettings.app("Apis", "Hyd", "BaseUrl")));
9 months ago
// Http请求方式2使用HttpClientFactory
//services.AddHttpClient(HttpEnum.Hyd.ToString(), c =>
//{
// c.BaseAddress = new Uri(AppSettings.app("Apis", "Hyd", "BaseUrl"));
//});
//services.AddSingleton<IHttpPollyHelper, HttpPollyHelper>();
//#region 方式2可配合Polly策略
9 months ago
//var retryPolicy = HttpPolicyExtensions
//.HandleTransientHttpError()
//.Or<TimeoutRejectedException>() // 若超时则抛出此异常
//.WaitAndRetryAsync(new[]
//{
// TimeSpan.FromSeconds(1),
// TimeSpan.FromSeconds(5),
// TimeSpan.FromSeconds(10)
//});
9 months ago
//// 为每个重试定义超时策略
//var timeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(10);
9 months ago
//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);
9 months ago
//#endregion
}
}
}