为同步Web api调用c#

时间:2019-06-20 13:26:45

标签: c# .net-core polly

我已经为HttpClient实施了以下Polly策略。

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));
    }
}

下面是Web 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的同步调用,因为我想等待响应出现。 在这种情况下,我的问题是,我需要在Polly中创建同步策略吗?如何?

还有一个问题,超时策略将适用于整个重试。我是否还需要为单次重试超时创建一个策略?

有帮助吗?

0 个答案:

没有答案