gpt4 book ai didi

c# - 如何在.net core 2.2 的启动文件中注册polly?

转载 作者:太空宇宙 更新时间:2023-11-03 20:48:59 25 4
gpt4 key购买 nike

我正在我的 .net core 2.2 应用程序中实现 polly。对于 HttpClient,有一个 nuget Microsoft.Extensions.Http.Polly 可用于在启动时注册任何 polly 模式(断路器或重试)。但是我如何将 polly 用于其他异常,如“SqlException”。举个这个 block 的例子:

        Policy
.Handle<SqlException>(ex => ex.Number == (int)SqlHandledExceptions.DatabaseNotCurrentlyAvailable)
.CircuitBreakerAsync(
// number of exceptions before breaking circuit
exceptionsAllowedBeforeBreaking,
// time circuit opened before retry
TimeSpan.FromSeconds(30),
OnBreak,
OnReset,
OnHalfOpen)
.WithPolicyKey($"F1.{PolicyKeys.SqlCircuitBreakerAsyncPolicy}"),

我想在启动文件中注册这个策略来处理sql异常。我该怎么做?

最佳答案

Polly 提供了 PolicyRegistry 的概念用于维护政策集合。

对于与 http 调用不直接相关的策略,推荐的 DI 方法是 register a PolicyRegistry with DIStartUp 期间并使用策略填充该注册表,也在 StartUp 阶段。

然后,使用策略的代码可以通过 DI 获取 IReadOnlyPolicyRegistry,并使用 the patterns shown in the Polly documentation 从注册表中检索适当的策略。 .


(为了信息的完整性:PolicyRegistry 方法 can also be used with HttpClientFactory and HttpClient。)

关于c# - 如何在.net core 2.2 的启动文件中注册polly?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57408823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com