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();
            }
        }
    }
}
posted @ 2020-09-25 17:27  清枫林  阅读(1218)  评论(0编辑  收藏  举报