我的服务定义:
var host = new HostBuilder().ConfigureServices(services =>
{
services
.AddHttpClient<Downloader>()
.AddPolicyHandler((services, request) =>
HttpPolicyExtensions
.HandleTransientHttpError()
.Or<SocketException>()
.Or<HttpRequestException>()
.WaitAndRetryAsync(
new[] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(10) },
onRetry: (outcome, timespan, retryAttempt, context) =>
{
Console.WriteLine($"Delaying {timespan}, retrying {retryAttempt}.");
}));
services.AddTransient<Downloader>();
}).Build();
Downloader
的实现:
class Downloader
{
private HttpClient _client;
public Downloader(IHttpClientFactory factory)
{
_client = factory.CreateClient();
}
public Download()
{
await _client.GetAsync(new Uri("localhost:8800")); // A port that no application is listening
}
}
通过这种设置,我希望看到尝试查询端点的三次尝试,并在控制台上打印日志消息(我也曾尝试过使用记录器,但在这里为了简单起见仅使用控制台)。
但实际上我看到的是未处理的异常消息(我只期望在重试和打印日志后才会看到它)。
未经处理的异常:System.Net.Http.HttpRequestException:无法建立连接,因为目标计算机积极拒绝。 (127.0.0.1:8800) ---> System.Net.Sockets.SocketException(10061):无法建立连接,因为目标计算机积极拒绝。
600
秒,并相应地增加了客户端的超时时间),这显然是一个明显的等待时间;但我并没有注意到那么长的等待时间! :) 它会在控制台上快速抛出异常并退出。 - Dr. Strangeloveservices.AddTransient<Downloader>();
,似乎会得到一个与使用 poly 配置的不同客户端实例 (https://www.stevejgordon.co.uk/httpclientfactory-named-typed-clients-aspnetcore),同时将Downloader(IHttpClientFactory
更改为Downloader(HttpClient
可以解决这个问题。我有点困惑,因为大多数 MSFT 文档上的示例都使用客户端工厂。虽然我很乐意被证明是错误的,并且错误可能出现在其他地方。 - Dr. Strangelove