Example #1
0
 public ServiceResult CallSomeSlowCode()
 {
     try
     {
         return(_policy.Execute(() => _someService.SlowCode()));
     }
     catch (TimeoutRejectedException ex)
     {
         Log.Information($"Ups: {ex.Message}");
         return(ServiceResult.Timeout);
     }
 }
Example #2
0
        private static void Demo2()
        {
            try
            {
                //ISyncPolicy policy = Policy.Handle<Exception>().WaitAndRetry(new TimeSpan[] { TimeSpan.FromMilliseconds(1000), TimeSpan.FromMilliseconds(2000) });
                //ISyncPolicy policy = Policy.Handle<Exception>().RetryForever( );
                ISyncPolicy policy = Policy.Handle <Exception>().Retry();
                //RetryForever();
                //Policy.Handle<Exception>().Retry
                //Policy.Handle<Exception>().RetryForever
                //Policy.Handle<Exception>().Fallback
                //Policy.Handle<Exception>().CircuitBreaker
                //Policy.Handle<Exception>().WaitAndRetry
                policy.Execute(() =>
                {
                    Console.WriteLine("开始任务");

                    //if (Environment.TickCount % 2 == 0)
                    if (DateTime.Now.Second % 5 != 0)
                    {
                        throw new Exception("出错");
                    }
                    Console.WriteLine("完成任务");
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine("未处理异常" + ex);
            }
        }
 public static void Wrap()
 {
     try
     {
         ISyncPolicy policyException = Policy.Handle <TimeoutRejectedException>()  //只针对超时异常
                                       .Fallback(() =>
         {
             Console.WriteLine("fallback");
         });
         ISyncPolicy policytimeout = Policy.Timeout(2, Polly.Timeout.TimeoutStrategy.Pessimistic);//乐观和悲观
         //ISyncPolicy policy3 = policyException.Wrap(policytimeout);//
         ISyncPolicy policy3 = Policy.Wrap(policyException, policytimeout);
         policy3.Execute(() =>
         {
             Console.WriteLine("开始任务");
             Thread.Sleep(5000);
             // throw new Exception();
             Console.WriteLine("完成任务");
         });
     }
     catch (Exception ex)
     {
         Console.WriteLine("未处理异常" + ex.GetType() + ":" + ex.Message);
     }
 }
Example #4
0
 internal static TResult Implementation <TResult>(
     Func <Context, CancellationToken, TResult> func,
     Context context,
     CancellationToken cancellationToken,
     ISyncPolicy <TResult> outerPolicy,
     ISyncPolicy <TResult> innerPolicy)
 => outerPolicy.Execute((ctx, ct) => innerPolicy.Execute(func, ctx, ct), context, cancellationToken);
Example #5
0
        public static void Case1()
        {
            ISyncPolicy policy = Policy.Handle <ArgumentException>()
                                 .Fallback(() =>
            {
                Console.WriteLine("Error occured");
            });

            policy.Execute(() =>
            {
                //try
                //{
                Console.WriteLine("Job Start");
                throw new ArgumentException("sdada");
                var ss = SumNum();


                Console.WriteLine($"Result {ss}");
                //}
                //catch (AggregateException ex)
                //{
                //    Console.WriteLine("我是错误的方法");
                //}
                //finally
                //{
                //    Console.WriteLine("Job End");
                //}
                //throw new ArgumentException("Hello Polly!");
            });
        }
Example #6
0
 /// <summary>
 /// Polly简单使用
 /// </summary>
 private static void SimpleUse()
 {
     try
     {
         ISyncPolicy policy = Policy.Handle <ArgumentException>(ex => ex.Message == "年龄参数错误")
                              .Fallback(() =>
         {
             Console.WriteLine("出错了");
         }, ex =>
         {
             Console.WriteLine("详细异常对象" + ex);
         });
         policy.Execute(() =>
         {
             //这里是可能会产生问题的业务系统代码
             Console.WriteLine("开始任务");
             throw new ArgumentException("年龄参数错误");
             //throw new Exception("haha");
             //Console.WriteLine("完成任务");
         });
     }
     catch (Exception ex)
     {
         Console.WriteLine($"未处理异常:{ex}");
     }
 }
Example #7
0
 internal static void Implementation(
     Action <Context, CancellationToken> action,
     Context context,
     CancellationToken cancellationToken,
     ISyncPolicy outerPolicy,
     ISyncPolicy innerPolicy)
 => outerPolicy.Execute((ctx, ct) => innerPolicy.Execute(action, ctx, ct), context, cancellationToken);
Example #8
0
        /// <summary>
        /// 超时处理
        /// 用途:请求网络接口,避免接口长期没有响应造成系统卡死。
        /// </summary>
        private static void Timeout()
        {
            ISyncPolicy policy = Policy.Handle <Exception>()
                                 .Fallback(() =>
            {
                Console.WriteLine("执行出错");
            }, ex =>
            {
                Console.WriteLine("详细异常对象" + ex);
            });

            policy = policy.Wrap(Policy.Timeout(2, TimeoutStrategy.Pessimistic));

            policy.Execute(() =>
            {
                Console.WriteLine("开始任务");
                Thread.Sleep(5000);
                Console.WriteLine("完成任务");
            });

            //        ISyncPolicy policy = Policy.Handle<TimeoutRejectedException>()
            //.Retry(1);
            //        policy = policy.Wrap(Policy.Timeout(3, TimeoutStrategy.Pessimistic));
            //        policy.Execute(() =>
            //        {
            //            Console.WriteLine("开始任务");
            //            Thread.Sleep(5000);
            //            Console.WriteLine("完成任务");
            //        });
        }
Example #9
0
        /// <summary>
        /// 重试处理
        /// </summary>
        private static void Retry()
        {
            int i = 0;

            try
            {
                ISyncPolicy policy = Policy.Handle <Exception>()
                                     .RetryForever();//一直重试
                policy.Execute(() =>
                {
                    Console.WriteLine("开始任务" + (++i));
                    if (DateTime.Now.Second % 2 != 0)
                    {
                        throw new Exception("出错");
                    }

                    Console.WriteLine("完成任务");
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"未处理异常:{ex}");
            }

            //RetryForever()是一直重试直到成功
            //Retry()是重试最多一次;
            //Retry(n)是重试最多n次;
            //WaitAndRetry()可以实现“如果出错等待100ms再试还不行再等150ms秒。。。。”,重载方法很多,一看就懂,不再一一介绍。还有WaitAndRetryForever。
        }
Example #10
0
        public static void Fusing()
        {
            Action <Exception, TimeSpan> onBreak = (exception, timespan) =>
            {
                Console.WriteLine("1");
            };
            Action onReset = () =>
            {
                Console.WriteLine("2");
            };
            ISyncPolicy policy = Policy.Handle <Exception>().CircuitBreaker(3, TimeSpan.FromSeconds(20), onBreak, onReset);

            while (true)
            {
                try
                {
                    policy.Execute(() =>
                    {
                        Console.WriteLine("任务开始");

                        throw new Exception("出错了");

                        Console.WriteLine("任务结束");
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine("---------------异常结果-------------- : " + ex.Message + "时间:" + DateTime.Now);
                }
                System.Threading.Thread.Sleep(5000);
            }
        }
Example #11
0
        private static void Main(string[] args)
        {
            var unstableService = new MrUnstable();

            ISyncPolicy redo1 = Policy.Handle <ApplicationException>()
                                .Retry(1,
                                       (exception, count) =>
            {
                Console.WriteLine($"ApplicationException, exception:{exception.Message}, count:{count}");
            });

            ISyncPolicy benFallback = Policy.Handle <ApplicationException>()
                                      .Fallback(() =>
            {
                Console.WriteLine("Execute Fallback action");
            }, ex =>
            {
                Console.WriteLine($"on fallback, exception message:{ex.Message.ToString()}");
            });

            benFallback.Execute(() =>
            {
                redo1.Execute(() =>
                {
                    unstableService.SpecificException(new ApplicationException());
                });
            });

            Console.Read();
        }
Example #12
0
        public static void RetryDowngrade()
        {
            try
            {
                //降级处理程序
                ISyncPolicy policy = Policy.Handle <Exception>()
                                     .Fallback(() =>
                {
                    Console.WriteLine("降级成功");
                });
                //配置重试次数
                ISyncPolicy policy2 = Policy.Handle <Exception>().Retry(3, (exception, retryCount, context) =>
                {
                    Console.WriteLine(retryCount);
                });
                //合并
                ISyncPolicy mainPolicy = Policy.Wrap(policy, policy2);
                mainPolicy.Execute(() =>
                {
                    Console.WriteLine("任务开始");

                    throw new Exception("出错了");

                    Console.WriteLine("任务结束");
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine("异常结果 : " + ex.Message);
            }
        }
        public static void CircuitBreaker()
        {
            int         i      = 0;
            ISyncPolicy policy = Policy
                                 .Handle <Exception>()
                                 .CircuitBreaker(6, TimeSpan.FromSeconds(5));//连续出错6次之后熔断5秒(不会再去尝试执行业务代码)。

            while (true)
            {
                Console.WriteLine("开始Execute");
                try
                {
                    policy.Execute(() =>
                    {
                        i++;
                        Console.WriteLine("开始任务");
                        if (i < 8)
                        {
                            throw new Exception("出错");
                        }

                        Console.WriteLine("完成任务");
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine("execute出错" + ex.GetType() + ":" + ex.Message);
                }
                Thread.Sleep(1000);
            }
        }
        public static void RetryForever()
        {
            try
            {
                ISyncPolicy policy = Policy.Handle <Exception>()
                                     //.WaitAndRetry(new TimeSpan[] { TimeSpan.FromMilliseconds(1000), TimeSpan.FromMilliseconds(2000) });
                                     .RetryForever();

                policy.Execute(() =>
                {
                    Console.WriteLine("开始任务");

                    //if (Environment.TickCount % 2 == 0)
                    if (DateTime.Now.Second % 10 != 0)
                    {
                        throw new Exception("出错");
                    }
                    Console.WriteLine("完成任务");
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine("未处理异常" + ex);
            }
        }
Example #15
0
 internal static TResult Implementation <TResult>(
     Func <Context, CancellationToken, TResult> func,
     Context context,
     CancellationToken cancellationToken,
     ISyncPolicy outerPolicy,
     ISyncPolicy innerPolicy)
 {
     return(outerPolicy.Execute <TResult>((ctx, ct) => innerPolicy.Execute <TResult>(func, ctx, ct), context, cancellationToken));
 }
Example #16
0
        /// <inheritdoc />
        public void Send(CefMessage message)
        {
            var syslogMessage    = _serializer.Serialize(message);
            var stream           = new MemoryStream(_serializer.Serialize(syslogMessage));
            var syslogMessageStr = new StreamReader(stream).ReadToEnd();

            Logger.LogInfoFormat("Send syslog message: {0}", syslogMessageStr);
            _policy.Execute(() => SendInternal(message));
        }
 public IRestResponse Execute(IRestRequest request)
 {
     if (null == request)
     {
         return(null);
     }
     if (null == _pollyRetPolicy)
     {
         return(null);
     }
     return(_pollyRetPolicy.Execute(() => _innerService.Execute(request)));
 }
Example #18
0
 public IRestResponse Execute(IRestRequest request)
 {
     if (null == request)
     {
         return(null);
     }
     if (null == _pollyRetPolicyGeneric)
     {
         return(null);
     }
     return(_pollyRetPolicyGeneric.Execute(() => (TResult)_innerService.Execute(request)));
 }
        /// <summary>
        /// Sends a new message to an existing queue
        /// </summary>
        /// <param name="messageToSend">The message to send.</param>
        /// <param name="data">The additional data.</param>
        /// <returns></returns>
        public IQueueOutputMessage Send(IMessage messageToSend, IAdditionalMessageData data)
        {
            IQueueOutputMessage result = null;

            if (_policy == null)
            {
                _policies.Registry.TryGet(_policies.Definition.SendMessage, out _policy);
            }

            if (_policy != null)
            {
                _policy.Execute(() => result = _handler.Send(messageToSend, data));
            }
            else //no policy found
            {
                result = _handler.Send(messageToSend, data);
            }
            return(result);
        }
Example #20
0
 public override void Open()
 {
     _retryPolicy.Execute(() =>
     {
         if (InnerConnection.State != ConnectionState.Open)
         {
             InnerConnection.Open();
         }
     });
 }
        /// <summary>
        /// Protect yourself against a missing policy by using NoOp
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public string UseRegistryWithNoOp(int input)
        {
            ISyncPolicy policy =
                _registry.ContainsKey("DefaultRetry")
                ? _registry.Get <ISyncPolicy>("DefaultRetry")
                : Policy.NoOp();

            var response = policy.Execute(() => dbContext.First(r => r.Key == input));

            return(response.Value);
        }
Example #22
0
        /// <summary>
        /// Executes the get data object enumerable asynchronous.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query">The query.</param>
        /// <param name="policy">The policy.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">policy</exception>
        public IEnumerable <T> ExecuteGetDataObjectEnumerable <T>(string query, ISyncPolicy policy) where T : class
        {
            //Check for null
            if (policy == null)
            {
                throw new ArgumentNullException(nameof(policy));
            }

            //Return this back to the caller
            return(policy.Execute(() => ExecuteSQL.GetDataObjectEnumerable <T>(QueryCommandType, query)));
        }
Example #23
0
        protected override void PerformProceed(IInvocation invocation)
        {
            ISyncPolicy policy = Policy.Handle <ArgumentException>().Fallback(() =>
            {
                Console.WriteLine("参数错误,直接捕捉起来干掉");
            });

            policy.Execute(() =>
            {
                base.PerformProceed(invocation);
            });
        }
        private void ProcessMessage(ConsumeResult <string, TPayload> consumeResult, Action <AgnosticMessage <TPayload> > processingAction)
        {
            var executionContext = CreateNewExecutionContext(consumeResult);

            resiliencePolicy.Execute((context) =>
            {
                var message = MapFromKafkaMessage(consumeResult);
                processingAction(message);

                logger.LogInformation($"Consumed message successfully processed: {consumeResult.TopicPartitionOffset}");
            }, executionContext);
        }
Example #25
0
        /// <summary>
        /// Utility method for executing an Ad-Hoc query or stored procedure without a transaction
        /// </summary>
        /// <param name="policy"></param>
        /// <param name="query">The query command text or name of stored procedure to execute against the data store</param>
        /// <returns>Returns the number of rows affected by this query as a <see cref="int"/></returns>
        public int ExecuteNonQuery(string query, ISyncPolicy policy)

        {
            //Check for null
            if (policy == null)
            {
                throw new ArgumentNullException(nameof(policy));
            }

            //Return this back to the caller
            return(policy.Execute(() => ExecuteSQL.ExecuteNonQuery(QueryCommandType, query)));
        }
        protected async Task <CloudQueue> GetQueueAsync(string name)
        {
            var queue = _cachingPolicy.Execute(context =>
            {
                var newQueue = QueueClient.GetQueueReference(name);
                newQueue.CreateIfNotExistsAsync().ConfigureAwait(false);

                return(newQueue);
            }, new Context(name));

            return(await Task.FromResult(queue));
        }
Example #27
0
 public IRestResponse Execute(IRestRequest request)
 {
     if (null == _pollyRetPolicyGeneric)
     {
         throw new AggregateException(nameof(_pollyRetPolicyGeneric) + " is  null");
     }
     return(_pollyRetPolicyGeneric.Execute(() =>
     {
         if (null == request)
         {
             throw new AggregateException(nameof(request) + " is  null");
         }
         return (TResult)_innerService.Execute(request);
     }));
 }
        public void InterceptSynchronous(IInvocation invocation)
        {
            ISyncPolicy policy = _policyFactory?.GetSyncPolicy(invocation.Method);

            if (policy != null)
            {
                Action action = () => invocation.Proceed();
                policy.Execute(action);
            }
            else
            {
                invocation.Proceed();
            }
        }
Example #29
0
 /// <inheritdoc />
 public void Handle(TCommand command)
 {
     if (_policy == null)
     {
         _policies.Registry.TryGet(TransportPolicyDefinitions.RetryCommandHandler, out _policy);
     }
     if (_policy != null)
     {
         _policy.Execute(() => _decorated.Handle(command));
     }
     else //no policy found
     {
         _decorated.Handle(command);
     }
 }
Example #30
0
        /// <summary>
        /// 降级
        /// </summary>
        static void FallbackTest()
        {
            ISyncPolicy policy = Policy.Handle <ArgumentException>()
                                 .Fallback(() =>
            {
                Console.WriteLine("Error occured,runing fallback");
            });

            policy.Execute(() =>
            {
                Console.WriteLine("Job Start");

                throw new ArgumentException("Hello Polly!");
            });
        }