You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
2.5 KiB
66 lines
2.5 KiB
3 weeks ago
|
using Microsoft.Extensions.DependencyInjection;
|
||
|
using Polly;
|
||
|
using Polly.Extensions.Http;
|
||
|
using System;
|
||
|
using System.Net.Http;
|
||
|
using Polly.Retry;
|
||
|
using Polly.Timeout;
|
||
|
using Polly.CircuitBreaker;
|
||
|
using Microsoft.Extensions.Http.Resilience;
|
||
|
|
||
|
namespace medical.transfomer.business
|
||
|
{
|
||
|
/// <summary>
|
||
|
/// 应用程序启动扩展方法
|
||
|
/// </summary>
|
||
|
public static class StartupExtensions
|
||
|
{
|
||
|
/// <summary>
|
||
|
/// 注册医保服务所需的服务
|
||
|
/// </summary>
|
||
|
public static IServiceCollection AddMedicalInsuranceServices(this IServiceCollection services, string baseUrl)
|
||
|
{
|
||
|
// 注册HttpClient工厂
|
||
|
services.AddHttpClient("MedicalInsurance", client =>
|
||
|
{
|
||
|
client.BaseAddress = new Uri(baseUrl);
|
||
|
client.DefaultRequestHeaders.Add("Accept", "application/json");
|
||
|
client.DefaultRequestHeaders.Add("User-Agent", "MedicalInsuranceClient");
|
||
|
client.Timeout = TimeSpan.FromSeconds(30);
|
||
|
})
|
||
|
.AddResilienceHandler("MedicalInsuranceResilienceHandler", builder =>
|
||
|
{
|
||
|
// 添加重试策略
|
||
|
builder.AddRetry(new RetryStrategyOptions<HttpResponseMessage>
|
||
|
{
|
||
|
ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
|
||
|
.Handle<HttpRequestException>()
|
||
|
.HandleResult(r => !r.IsSuccessStatusCode),
|
||
|
MaxRetryAttempts = 3,
|
||
|
Delay = TimeSpan.FromSeconds(1),
|
||
|
BackoffType = DelayBackoffType.Exponential
|
||
|
});
|
||
|
|
||
|
// 添加断路器策略
|
||
|
builder.AddCircuitBreaker(new CircuitBreakerStrategyOptions<HttpResponseMessage>
|
||
|
{
|
||
|
ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
|
||
|
.Handle<HttpRequestException>()
|
||
|
.HandleResult(r => !r.IsSuccessStatusCode),
|
||
|
FailureRatio = 0.5, // 50%失败率
|
||
|
MinimumThroughput = 10, // 最小样本数
|
||
|
SamplingDuration = TimeSpan.FromSeconds(30), // 采样时间窗口
|
||
|
BreakDuration = TimeSpan.FromMinutes(1) // 断路时间
|
||
|
});
|
||
|
|
||
|
// 添加超时策略
|
||
|
builder.AddTimeout(TimeSpan.FromSeconds(30));
|
||
|
});
|
||
|
|
||
|
// 注册转换工厂
|
||
|
services.AddScoped<TransformerFactory>();
|
||
|
|
||
|
return services;
|
||
|
}
|
||
|
}
|
||
|
}
|