重试HttpClient不成功的请求

重试HttpClient不成功的请求,第1张

重试HttpClient不成功的请求

代替实施包裹该重试功能的

HttpClient
,可以考虑构成
HttpClient
HttpMessageHandler
内部执行所述重试逻辑。例如:

public class RetryHandler : DelegatingHandler{    // Strongly consider limiting the number of retries - "retry forever" is    // probably not the most user friendly way you could respond to "the    // network cable got pulled out."    private const int MaxRetries = 3;    public RetryHandler(HttpMessageHandler innerHandler)        : base(innerHandler)    { }    protected override async Task<HttpResponseMessage> SendAsync(        HttpRequestMessage request,        CancellationToken cancellationToken)    {        HttpResponseMessage response = null;        for (int i = 0; i < MaxRetries; i++)        { response = await base.SendAsync(request, cancellationToken); if (response.IsSuccessStatusCode) {     return response; }        }        return response;    }}public class BusinessLogic{    public void FetchSomeThingsSynchronously()    {        // ...        // Consider abstracting this construction to a factory or IoC container        using (var client = new HttpClient(new RetryHandler(new HttpClientHandler())))        { myResult = client.PostAsync(yourUri, yourHttpContent).Result;        }        // ...    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5045159.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-15

发表评论

登录后才能评论

评论列表(0条)

保存