如何在Flurl.Http上使用Polly?

时间:2016-11-22 15:31:27

标签: c# httpresponse polly flurl

目前我有这个要求:

await url
    .SetQueryParams(queryString)
    .SetClaimsToken()
    .GetJsonAsync<T>()

我现在开始使用Polly(https://github.com/App-vNext/Polly)来处理重试并提供更好的用户体验。例如,由于网络连接不良,第一次尝试时不会“挂断”用户。这是我试图使用的例子:

int[] httpStatusCodesWorthRetrying = { 408, 500, 502, 503, 504 };
Policy
    .Handle<HttpException>()
    .OrResult<HttpResponse>(r => httpStatusCodesWorthRetrying.Contains(r.StatusCode))
    .WaitAndRetryAsync(new[] {
                    TimeSpan.FromSeconds(1),
                    TimeSpan.FromSeconds(2),
                    TimeSpan.FromSeconds(3)
                })
    .ExecuteAsync( await url... )

但它需要HttpResponse作为返回类型。正如您从我的Flurl示例中看到的那样,它返回T,即使它是HttpResponseT只是用于反序列化StringContent的类型。

第一个例子根本不起作用,因为我在PCL中使用它并且我无法在那里获得对System.Web的引用。所以我尝试了这个:

Policy
    .HandleResult(HttpStatusCode.InternalServerError)
    .OrResult(HttpStatusCode.BadGateway)
    .OrResult(HttpStatusCode.BadRequest)
    .WaitAndRetryAsync(new[] {
        TimeSpan.FromSeconds(1),
        TimeSpan.FromSeconds(2),
        TimeSpan.FromSeconds(3)
    })
    .ExecuteAsync(async () =>
    {
        await url...
    });

但是这个也行不通,因为Polly希望HttpStatusCode作为返回类型。所以我的问题是:我如何告诉polly处理那些HttpStatusCode并仍允许我返回类型T

3 个答案:

答案 0 :(得分:14)

你不应该使用像GetJsonAsync<T>()这样的便利方法,因为Flurl会对非2XX响应(或者你configure)抛出异常,这应该允许它与波莉玩得很好。只需删除原始代码中的.Handle<HttpException>.OrResult<HttpResponse>部分,然后处理FlurlHttpException

T poco = await Policy
    .Handle<FlurlHttpException>(ex => httpStatusCodesWorthRetrying.Contains((int)ex.Call.Response.StatusCode))
    .WaitAndRetryAsync(...)
    .ExecuteAsync(() => url
        .SetQueryParams(queryString)
        .SetClaimsToken()
        .GetJsonAsync<T>());

只是建议进一步清理:

T poco = await Policy
    .Handle<FlurlHttpException>(IsWorthRetrying)
    .WaitAndRetryAsync(...)
    .ExecuteAsync(() => url
        .SetQueryParams(queryString)
        .SetClaimsToken()
        .GetJsonAsync<T>());

private bool IsWorthRetrying(FlurlHttpException ex) {
    switch ((int)ex.Call.Response.StatusCode) {
        case 408:
        case 500:
        case 502:
        case 504:
            return true;
        default:
            return false;
    }
}

答案 1 :(得分:8)

Polly可以将通过策略执行的委托返回的任何值解释为错误。但是,正如您所观察到的,在您发布的示例中对.GetJsonAsync<T>()的调用:

await url
    .SetQueryParams(queryString)
    .SetClaimsToken()
    .GetJsonAsync<T>()

正在返回T。该调用通过直接将Json反序列化隐藏到HttpResponseMessage来隐藏T

你需要在flurl中使用一个重载,它会返回HttpResponseMessage左右的内容。我没有使用过flurl,但this overload返回Task<HttpResponseMessage>看起来很有希望。你可能会做类似的事情:

List<int> httpStatusCodesWorthRetrying = new List<int>(new[] {408, 500, 502, 503, 504});
HttpResponseMessage response = await Policy
    .Handle<HttpRequestException>() 
    .Or<OtherExceptions>() // add other exceptions if you find your call may throw them, eg FlurlHttpException
    .OrResult<HttpResponseMessage>(r => httpStatusCodesWorthRetrying.Contains((int)r.StatusCode))
    .WaitAndRetryAsync(new[] {
                    TimeSpan.FromSeconds(1),
                    TimeSpan.FromSeconds(2),
                    TimeSpan.FromSeconds(3)
                })
    .ExecuteAsync(() => 
       url
        .SetQueryParams(queryString)
        .SetClaimsToken()
        .GetAsync()
    );

T responseAsT = await Task.FromResult(response).ReceiveJson<T>();

建议最后调用.ReceiveJson<T>()只是将原始调用.GetJsonAsync<T>() here的flurl源代码与替代.GetAsync(); here进行比较

当然你可以把它全部包装成flurl上的一个简洁的扩展helper方法,也许是这样的:

async T GetJsonAsyncResiliently<T>(this IFlurlClient client, Policy policy) // OR (if preferred): this Url url instead of IFlurlClient client
{
    return await Task.FromResult(policy.ExecuteAsync(() => client.GetAsync())).ReceiveJson<T>();
}

编辑:在指向IFlurlClient上的方法时,我可能已针对您的案例指出了错误的flurl重载。但是,Urlstring上的flurl中存在一组并行的扩展方法,因此适用相同的原则。

答案 2 :(得分:3)

通过设置可以用Polly配置的HttpClientFactory来配置Flurl并创建自定义HttpClientFactory

public class MyCustomHttpClientFactory : DefaultHttpClientFactory, IMyCustomHttpClientFactory
{
    private readonly HttpClient _httpClient;
    public MyCustomHttpClientFactory(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }
    public override HttpClient CreateHttpClient(HttpMessageHandler handler)
    {
        return _httpClient;
    }
}

ConfigureServices中通过以下方式注册该服务:

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddHttpClient<IMyCustomHttpClientFactory, MyCustomHttpClientFactory>()
        .SetHandlerLifetime(...)
        .AddPolicyHandler(....);
}

并将该工厂分配给Flurl:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Get HttpClientFactory and Configure Flurl to use it.
    var factory = (IMyCustomHttpClientFactory)app.ApplicationServices.GetService(typeof(IMyCustomHttpClientFactory));
    FlurlHttp.Configure((settings) => settings.HttpClientFactory = factory);
}