zoukankan      html  css  js  c++  java
  • 使用Polly让程序有Retry的机制

    有时候我们需要调用其他API的时候出现暂时连接不通超时的情况,那这时候可以通过Polly进行Retry。

    1、从nuget引用polly,

    2、定义需要处理的异常有哪些,比如

    Policy.Handle<TimeoutException>().Or<FormatException>()

    3、异常发生时候需要定义重试几次,等多久后再重试,比如

    var policy = Policy.Handle<TimeoutException>().RetryAsync(3, (exception, retryCount) =>
    {

    });

    4、代码跟policy结合起来的demo如下:

           private static Logger logger = LogManager.GetCurrentClassLogger();
    
            private static void Main(string[] args)
            {
                var policy = Policy.Handle<TimeoutException>()
                    .WaitAndRetryAsync(5, retryAttempt => TimeSpan.FromSeconds(5), (exception, retryCount) =>
                {
                    logger.Error(exception);
                });
    
                var result = policy.ExecuteAsync(() => Test());
            }
    
            private static async Task Test()
            {
                using (var httpClient = new HttpClient())
                {
                    var response = httpClient.GetAsync("http://news.cnblogs.com/Category/GetCategoryList?bigCateId=11&loadType=0").Result;
                    await response.Content.ReadAsStringAsync();
                }
            }
  • 相关阅读:
    exit()和_exit()函数(转)
    C语言struct内存占用问题 (转)
    C语言中memset函数(转)
    STDIN_FILENO与stdin区别(转)
    stderr,strerror,errno,perror,论坛大神的回答!
    C++ 函数模版
    C++ 内置函数
    offsetof
    LockSupportDemo
    读写锁,await和signa
  • 原文地址:https://www.cnblogs.com/hj4444/p/4746616.html
Copyright © 2011-2022 走看看