zoukankan      html  css  js  c++  java
  • C# 异常重试策略

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using Polly;
    using Polly.Bulkhead;
    using Polly.CircuitBreaker;
    using Polly.Fallback;
    using Polly.NoOp;
    using Polly.Registry;
    using Polly.Retry;
    using Polly.Timeout;
    using Polly.Utilities;
    using Polly.Wrap;
    using System.Net.Http;
    
    namespace CircuitBreak_Test
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
    
                try
                {
                    var retryTwoTimesPolicy =
                         Policy
                             .Handle<DivideByZeroException>()
                             .Retry(3, (ex, count) =>
                             {
                                 Console.WriteLine("执行失败! 重试次数 {0}", count);
                                 Console.WriteLine("异常来自 {0}", ex.GetType().Name);
                             });
                    retryTwoTimesPolicy.Execute(() =>
                    {
                        Compute();
                    });
                }
                catch (DivideByZeroException e1)
                {
                    Console.WriteLine($"Excuted Failed,Message: ({e1.Message})");
    
                }
    
                Policy policy = Policy.Handle<TimeoutException>()
                   .WaitAndRetryAsync(5, retryAttempt => TimeSpan.FromSeconds(5), (exception, retryCount) =>
                   {
                       //logger.Error(exception);
                       string xx = "";
                   });
    
                var result = policy.ExecuteAsync(() => Test());
    
    
                Policy _circuitBreakerPolicy = Policy
                    .Handle<HttpRequestException>()
                    .Or<TimeoutRejectedException>()
                    .Or<TimeoutException>()
                    .CircuitBreakerAsync(
                        exceptionsAllowedBeforeBreaking: 5,
                        durationOfBreak: new TimeSpan(),
                        onBreak: (ex, breakDelay) =>
                        {
                            
                        },
                        onReset: () => { },
                        onHalfOpen: () => { }
                        );
    
                var fallBackPolicy =
                   Policy<string>
                       .Handle<Exception>()
                       .Fallback("执行失败,返回Fallback");
    
                var fallBack = fallBackPolicy.Execute(() =>
                {
                    throw new Exception();
                });
                Console.WriteLine(fallBack);
    
               
            }
    
            static int Compute()
            {
                var a = 0;
                return 1 / a;
            }
    
            private static async Task Test()
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    var response = httpClient.GetAsync("http://news1.cnblogs.com/Category/GetCategoryList?bigCateId=11&loadType=0").Result;
                    await response.Content.ReadAsStringAsync();
                }
            }
        }
    }
  • 相关阅读:
    解决Original error: Could not proxy command to remote server. Original error: Error: socket hang up
    python各进制转换
    爬楼梯问题,yield学习总结
    微信开放平台API开发资料
    数据切分——Atlas读写分离Mysql集群的搭建
    svn SSL 错误:Key usage violation in certificate has been detected
    如何将一个空间里的内容全部复制到另一个空间,文件名不变
    SVN客户端安装 Linux
    Web端即时通讯技术盘点:短轮询、Comet、Websocket、SSE
    搭建SVN服务器
  • 原文地址:https://www.cnblogs.com/qingfenglin/p/13731415.html
Copyright © 2011-2022 走看看