Beispiel #1
0
        static async Task PollyTest()
        {
            var atr = new CRL.Core.Remoting.PollyAttribute();

            //atr.TimeOutTime = TimeSpan.FromMilliseconds(100);
            atr.CircuitBreakerCount = 2;
            atr.RetryCount          = 1;
            var pollyCtx = new Polly.Context();
            var response = await PollyExtension.InvokeAsync <string>(atr, async() =>
            {
                //await Task.Delay(200);
                throw new Exception("has error");
                return(await Task.FromResult(new CRL.Core.Remoting.PollyExtension.PollyData <string>()
                {
                    Data = "ok"
                }));
            }, "");

            if (pollyCtx.ContainsKey("msg"))
            {
                Console.WriteLine(pollyCtx["msg"]);
            }

            //var str = PollyExtension.Invoke(atr, () =>
            // {
            //    throw new Exception("has error");
            //    //System.Threading.Thread.Sleep(200);
            //     return new PollyExtension.PollyData<string>() { Error = "ok" };
            // }, "test");
            Console.WriteLine(response.ToJson());
        }
Beispiel #2
0
        protected T SendRequest <T>(PollyAttribute pollyAttr, Request.ImitateWebRequest request, string url, string httpMethod, string postArgs, string pollyKey, Func <string, T> dataCall)
        {
            //var pollyCtx = new Polly.Context();
            var pollyData = PollyExtension.Invoke(pollyAttr, () =>
            {
                var res = request.SendData(url, httpMethod.ToString(), postArgs, out string url2);
                return(new PollyExtension.PollyData <string>()
                {
                    Data = res
                });
            }, pollyKey);

            if (!string.IsNullOrEmpty(pollyData.Error))
            {
                ThrowError(pollyData.Error, "500");
            }
            //转换为指定的类型
            return(dataCall(pollyData.Data));
        }
Beispiel #3
0
        protected async Task <T> SendRequestAsync <T>(PollyAttribute pollyAttr, Request.ImitateWebRequest request, string url, string httpMethod, string postArgs, string pollyKey, Func <string, T> dataCall)
        {
            var pollyCtx = new Polly.Context();
            //var response = await request.SendDataAsync(url, httpMethod.ToString(), postArgs);
            var pollyData = await PollyExtension.InvokeAsync(pollyAttr, async() =>
            {
                var res = await request.SendDataAsync(url, httpMethod.ToString(), postArgs);
                return(new PollyExtension.PollyData <string>()
                {
                    Data = res
                });
            }, pollyKey);

            if (!string.IsNullOrEmpty(pollyData.Error))
            {
                ThrowError(pollyData.Error, "500");
            }
            //转换为指定的类型
            return(dataCall(pollyData.Data));
        }
        public static PollyData <T> Invoke <T>(PollyAttribute atr, Func <PollyData <T> > task, string policyKey)
        {
            if (atr == null)
            {
                try
                {
                    return(task());
                }
                catch (Exception ero)
                {
                    var msg = ero.Message;
                    if (ero is Request.RequestException)
                    {
                        msg = (ero as Request.RequestException).ToString();
                    }
                    return(new PollyData <T>()
                    {
                        Error = $"接口调用发生错误:{msg}"
                    });
                }
            }
            Policy <PollyData <T> > policy;
            var a = policies.TryGetValue(policyKey, out object _policy);

            if (_policy == null)
            {
                policy = Policy.NoOp <PollyData <T> >();
                if (atr.CircuitBreakerCount > 0)//熔断
                {
                    policy = policy.Wrap(Policy.Handle <Exception>().CircuitBreaker(atr.CircuitBreakerCount, atr.CircuitBreakerTime));
                    var policyFallBack = Policy <PollyData <T> > .Handle <Polly.CircuitBreaker.BrokenCircuitException>()
                                         .Fallback(() =>
                    {
                        return(new PollyData <T>()
                        {
                            Error = "接口调用被熔断"
                        });
                    });

                    policy = policyFallBack.Wrap(policy);
                }
                if (atr.TimeOutTime > TimeSpan.Zero)//超时
                {
                    policy = policy.Wrap(Policy.Timeout(() => atr.TimeOutTime, Polly.Timeout.TimeoutStrategy.Pessimistic));
                    var policyFallBack = Policy <PollyData <T> > .Handle <Polly.Timeout.TimeoutRejectedException>()
                                         .Fallback(() =>
                    {
                        return(new PollyData <T>()
                        {
                            Error = "接口调用超时"
                        });
                    });

                    policy = policyFallBack.Wrap(policy);
                }
                if (atr.RetryCount > 0)//重试
                {
                    policy = policy.Wrap(Policy.Handle <Exception>().WaitAndRetry(atr.RetryCount, b => atr.RetryInterval));
                }
                policies.TryAdd(policyKey, policy);
            }
            else
            {
                policy = _policy as Policy <PollyData <T> >;
            }
            try
            {
                return(policy.Execute(task));
            }
            catch (Exception ero)
            {
                var msg = ero.Message;
                if (ero is Request.RequestException)
                {
                    msg = (ero as Request.RequestException).ToString();
                }
                return(new PollyData <T>()
                {
                    Error = $"接口调用发生错误:{msg}"
                });
            }
        }
Beispiel #5
0
        public static async Task <PollyData <T> > InvokeAsync <T>(PollyAttribute atr, Func <Task <PollyData <T> > > task, string policyKey)
        {
            if (atr == null)
            {
                try
                {
                    return(await task());
                }
                catch (Exception ero)
                {
                    var msg       = ero.Message;
                    var errorCode = "";
                    if (ero is Request.RequestException)
                    {
                        var requestException = ero as Request.RequestException;
                        errorCode = requestException.ErrorCode;
                        msg       = requestException.ToString();
                    }
                    return(new PollyData <T>()
                    {
                        Error = $"接口调用发生错误:{msg}", ErrorCode = errorCode
                    });
                }
            }
            Policy <PollyData <T> > policy;
            var a = policies.TryGetValue(policyKey, out object _policy);

            if (_policy == null)
            {
                policy = Policy.NoOpAsync <PollyData <T> >();
                if (atr.CircuitBreakerCount > 0)//熔断
                {
                    policy = policy.WrapAsync(Policy.Handle <Exception>().CircuitBreakerAsync(atr.CircuitBreakerCount, atr.CircuitBreakerTime));
                    var policyFallBack = Policy <PollyData <T> >
                                         .Handle <Polly.CircuitBreaker.BrokenCircuitException>()
                                         .FallbackAsync((ctx, t) =>
                    {
                        return(Task.FromResult(new PollyData <T>()
                        {
                            Error = "接口调用被熔断"
                        }));
                    }, (ex, t) =>
                    {
                        return(Task.FromResult <PollyData <T> >(null));
                    });

                    policy = policyFallBack.WrapAsync(policy);
                }
                if (atr.TimeOutTime > TimeSpan.Zero)//超时
                {
                    policy = policy.WrapAsync(Policy.TimeoutAsync(() => atr.TimeOutTime, Polly.Timeout.TimeoutStrategy.Pessimistic));
                    var policyFallBack = Policy <PollyData <T> >
                                         .Handle <Polly.Timeout.TimeoutRejectedException>()
                                         .FallbackAsync((ctx, t) =>
                    {
                        return(Task.FromResult(new PollyData <T>()
                        {
                            Error = "接口调用超时"
                        }));
                    }, (ex, t) =>
                    {
                        return(Task.FromResult <PollyData <T> >(null));
                    });

                    policy = policyFallBack.WrapAsync(policy);
                }
                if (atr.RetryCount > 0)//重试
                {
                    policy = policy.WrapAsync(Policy.Handle <Exception>().WaitAndRetryAsync(atr.RetryCount, b => atr.RetryInterval));
                }
                policies.TryAdd(policyKey, policy);
            }
            else
            {
                policy = _policy as Policy <PollyData <T> >;
            }
            try
            {
                return(await policy.ExecuteAsync(task));
            }
            catch (Exception ero)
            {
                var msg = ero.Message;
                if (ero is Request.RequestException)
                {
                    msg = (ero as Request.RequestException).ToString();
                }
                return(new PollyData <T>()
                {
                    Error = $"接口调用发生错误:{msg}"
                });
            }
        }