Создайте политику Polly Retry для синхронного вызова API веб c # - PullRequest
0 голосов
/ 20 июня 2019

Я реализовал приведенные ниже политики Polly для HttpClient.

IHostBuilder hostBuilder = new HostBuilder().ConfigureServices((hostContext, services) =>
                                   {
                                       AppSettings appSettings = new AppSettings();
                                       IConfigurationRoot configuration = GetConfiguration();
                                       configuration.Bind("Configuration", appSettings);

                                    services.AddSingleton(appSettings);                                          services.AddHttpClient("WebAPI", client =>
                                       {
                                           client.BaseAddress = new Uri(appSettings.WebApiBaseAddress);
                                           client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                                       })
                                       .AddPolicyHandler(HttpClientPolicyHandler.WaitAndRetry(appSettings.RetryCount))
                                       .AddPolicyHandler(HttpClientPolicyHandler.Timeout(appSettings.TimeOut));

                                       services.AddHostedService<RDPersister>();
                                   });

        await hostBuilder.RunConsoleAsync();

public static class HttpClientPolicyHandler
{
    /// <summary>
    /// Create a Wait and Retry policy for HttpClient on the basis of specified Status Code and Timeout.
    /// </summary>
    /// <param name="retryCount">Number of retries.</param>
    /// <returns>Wait and Retry policy handler.</returns>
    public static IAsyncPolicy<HttpResponseMessage> WaitAndRetry(int retryCount)
    {
        return HttpPolicyExtensions.HandleTransientHttpError()
               .OrResult(msg => msg.StatusCode == HttpStatusCode.NotFound)
               .Or<TimeoutRejectedException>()
               .Or<HttpRequestException>()
               .WaitAndRetryAsync(retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
    }

    /// <summary>
    /// Create a Timeout policy for HttpClient.
    /// </summary>
    /// <param name="seconds">Timeout.</param>
    /// <returns>Timeout policy handler.</returns>
    public static IAsyncPolicy<HttpResponseMessage> Timeout(int seconds)
    {
        return Policy.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromSeconds(seconds));
    }
}

Ниже приведен асинхронный вызов веб-API

.
private async void CallWebApi(string webApiJsonMessage)
{
    try
    {
        HttpClient client = _httpClientFactory.CreateClient("WebAPI");
            string uri = "api/CalculateOrder";

        HttpResponseMessage response = await client.PostAsync(uri, new StringContent(webApiJsonMessage, Encoding.UTF8, "application/json"));
        string token = await response.Content.ReadAsStringAsync();

            if (response.IsSuccessStatusCode)
            {          
            }
            else
            {
            }
     }
     catch (Exception ex)
     {
         _logger.Error($"Exception occurred while calling WebAPI: {ex.Message} for message : {webApiJsonMessage}");
     }
 }

Но я хочу создать синхронный вызов WebAPI, так как хочу дождаться ответа. Мой вопрос, то в таком случае мне нужно создать политику синхронизации в Полли и как ??

И еще один вопрос: политика тайм-аута будет работать для всех попыток. Нужно ли создавать еще одну политику для тайм-аута одной попытки?

Любая помощь ??

...