2 回答

TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
其實(shí)我沒(méi)有使用自動(dòng)解壓,但實(shí)現(xiàn)這一點(diǎn)的方法是正確注冊(cè)http客戶端
services.AddHttpClient<MyCustomHttpClient>()
.ConfigureHttpMessageHandlerBuilder((c) =>
new HttpClientHandler()
{
AutomaticDecompression = System.Net.DecompressionMethods.GZip
}
)
.AddHttpMessageHandler((s) => s.GetService<MyCustomDelegatingHandler>())

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊
通過(guò) HttpClientBuilder 的 ConfigurePrimaryHttpMessageHandler() 方法定義主 HttpMessageHandler 更合適。請(qǐng)參閱下面的示例以配置類型化客戶端。
services.AddHttpClient<TypedClient>()
.ConfigureHttpClient((sp, httpClient) =>
{
var options = sp.GetRequiredService<IOptions<SomeOptions>>().Value;
httpClient.BaseAddress = options.Url;
httpClient.Timeout = options.RequestTimeout;
})
.SetHandlerLifetime(TimeSpan.FromMinutes(5))
.ConfigurePrimaryHttpMessageHandler(x => new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
})
.AddHttpMessageHandler(sp => sp.GetService<SomeCustomHandler>().CreateAuthHandler())
.AddPolicyHandlerFromRegistry(PollyPolicyName.HttpRetry)
.AddPolicyHandlerFromRegistry(PollyPolicyName.HttpCircuitBreaker);
您還可以通過(guò)使用 Polly 庫(kù)的特殊構(gòu)建器方法來(lái)定義錯(cuò)誤處理策略。在這個(gè)示例中,策略應(yīng)該被預(yù)定義并存儲(chǔ)到策略注冊(cè)服務(wù)中。
public static IServiceCollection AddPollyPolicies(
this IServiceCollection services,
Action<PollyPoliciesOptions> setupAction = null)
{
var policyOptions = new PollyPoliciesOptions();
setupAction?.Invoke(policyOptions);
var policyRegistry = services.AddPolicyRegistry();
policyRegistry.Add(
PollyPolicyName.HttpRetry,
HttpPolicyExtensions
.HandleTransientHttpError()
.WaitAndRetryAsync(
policyOptions.HttpRetry.Count,
retryAttempt => TimeSpan.FromSeconds(Math.Pow(policyOptions.HttpRetry.BackoffPower, retryAttempt))));
policyRegistry.Add(
PollyPolicyName.HttpCircuitBreaker,
HttpPolicyExtensions
.HandleTransientHttpError()
.CircuitBreakerAsync(
handledEventsAllowedBeforeBreaking: policyOptions.HttpCircuitBreaker.ExceptionsAllowedBeforeBreaking,
durationOfBreak: policyOptions.HttpCircuitBreaker.DurationOfBreak));
return services;
}
- 2 回答
- 0 關(guān)注
- 384 瀏覽
添加回答
舉報(bào)