備忘録

備忘録

HttpClientFactoryとPollyをコンソールアプリケーションで使用する方法

Ⅱ. やり方

1. 必要なパッケージをインストールする
Install-Package Microsoft.Extensions.Http.Polly
2. サンプルプログラムを書く
using Microsoft.Extensions.DependencyInjection;
using Polly;
using Polly.Extensions.Http;
using Polly.Timeout;
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace Test
{
  class Program
  {
    static async Task Main()
    {
      const string HttpClientName = "MyHttpClient";

      // HttpClientを生成する
      var policy = HttpPolicyExtensions
        .HandleTransientHttpError()
        .OrResult(msg => msg.StatusCode != HttpStatusCode.OK)
        .Or<TimeoutRejectedException>()
        .WaitAndRetryAsync(10, _ => TimeSpan.FromSeconds(1));

      var timeoutPolicy = Policy
        .TimeoutAsync<HttpResponseMessage>(TimeSpan.FromSeconds(10), TimeoutStrategy.Pessimistic);

      var services = new ServiceCollection();
      services
        .AddHttpClient(HttpClientName, x =>
        {
          // Pollyで制御するのでHttpClientのTimeoutは無制限に設定する
          // https://devadjust.exblog.jp/29756261/
          x.Timeout = Timeout.InfiniteTimeSpan;
        })
        .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
        {
          // Proxy = proxy
        })
        .AddPolicyHandler(policy)
        .AddPolicyHandler(timeoutPolicy);

      var provider = services.BuildServiceProvider();
      var factory = provider.GetRequiredService<IHttpClientFactory>();
      var client = factory.CreateClient(HttpClientName);

      var str = await client.GetStringAsync("http://example.com");
      Console.WriteLine(str);
    }
  }
}

実行結果

<!doctype html>
<html>
<head>
    <title>Example Domain</title>

    <meta charset="utf-8" />
以下省略