コード例 #1
0
        public void AddCustom_Should_AddLinkToPolicyInMemoryRepository()
        {
            // Arrange
            string linkKey       = "CustomLink";
            string template      = "/api/custom";
            var    policyBuilder = new PolicyBuilder <object>();

            // Act
            policyBuilder.AddCustom(o => o, linkKey, template);

            // Assert
            PolicyInMemoryRepository.LinksPolicyInMemory
            .Any(p => (p as PolicyInMemoryRepository.TemplatePolicy) != null &&
                 (p as PolicyInMemoryRepository.TemplatePolicy).Template.Equals(template))
            .Should().BeTrue();
        }
コード例 #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AsyncCachePolicy{TResult}"/> class.
        /// </summary>
        /// <param name="isPolicyEnabled">An overall enablement feature flag for enabling/disabling <see cref="AsyncCachePolicy{TResult}"/>.</param>
        /// <param name="policyBuilder">Builder class that holds the list of current execution predicates filtering TResult result values</param>
        /// <param name="agingStrategy">Cache aging strategy which controls when cache will become stale and expired.</param>
        /// <param name="cacheProvider">Provides the contract to access cache layer</param>
        /// <param name="loggingProvider">Provides the contract to logging <see cref="AsyncCachePolicy{TResult}"/> operations</param>
        internal AsyncCachePolicy(
            bool isPolicyEnabled,
            PolicyBuilder <TResult> policyBuilder,
            IAgingStrategy <TResult> agingStrategy,
            ICacheProvider cacheProvider,
            ILoggingProvider <TResult> loggingProvider)
            : base(policyBuilder)
        {
            agingStrategy.ThrowIfNull(nameof(agingStrategy));
            cacheProvider.ThrowIfNull(nameof(cacheProvider));
            loggingProvider.ThrowIfNull(nameof(loggingProvider));

            this.isPolicyEnabled = isPolicyEnabled;
            this.agingStrategy   = agingStrategy;
            this.cacheProvider   = cacheProvider;
            this.loggingProvider = loggingProvider;
        }
コード例 #3
0
        public async Task <IActionResult> Index()
        {
            CoreResult coreResult = new CoreResult();

            #region ServiceDiscovery

            var serviceProvider = new ConsulServiceProvider(new Uri("http://127.0.0.1:8500"));

            var _userServiceUrl = serviceProvider.CreateServiceBuilder(builder =>
            {
                builder.ServiceName  = "UserApi";
                builder.LoadBalancer = TypeLoadBalancer.RoundRobin;
                builder.UriScheme    = Uri.UriSchemeHttp;
            }).BuildAsync("/api/user/servicesdiscovery").Result;

            #endregion

            var polly = PolicyBuilder.CreatePolly();
            polly.Execute(() => {
                try
                {
                    var form = new Dictionary <string, string>()
                    {
                        { "phone", "18650482503" }
                    };
                    var response = _httpClient.PostAsync(_userServiceUrl.ToString(), new FormUrlEncodedContent(form)).Result;
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        coreResult.Success(response.Content.ReadAsStringAsync().Result);
                    }
                    else
                    {
                        coreResult.Failed(response.Content.ReadAsStringAsync().Result);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError("在重试之后失败");
                    throw new Exception(ex.Message);
                }
            });

            return(Content(coreResult.Message));
        }
コード例 #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RedisConnection"/> class.
        /// </summary>
        /// <param name="connectionString">Connection string to Redis</param>
        /// <param name="redisRetryPolicy">Retry policy</param>
        public RedisConnection(string connectionString, IRedisRetryPolicy redisRetryPolicy)
        {
            _setKeyChannel = "~SetKey~:" + _instanceId;

            _baseRetryPolicy = Policy.Handle<TimeoutException>()
                                     .Or<TimeoutException>()
                                     .Or<SocketException>()
                                     .Or<IOException>();  // for async
            _retryPolicy = GetBaseRetryPolicyBuilder().WaitAndRetry(redisRetryPolicy.SleepDurations);
            _retryPolicyAsync = GetBaseRetryPolicyBuilder().WaitAndRetryAsync(redisRetryPolicy.SleepDurations);

            var options = ConfigurationOptions.Parse(connectionString);
            ConfigureIfMissing(options, "abortConnect", connectionString, o => { o.AbortOnConnectFail = false; });
            ConfigureIfMissing(options, "allowAdmin", connectionString, o => { o.AllowAdmin = true; });

            _multiplexer = ConnectionMultiplexer.Connect(options);
            _multiplexer.PreserveAsyncOrder = false;

            SubscribeToEvents();
        }
コード例 #5
0
        private static PolicyBuilder BuildPolicyBuilderFromPollyTransientFailureExceptionsXMLFile()
        {
            return(ExceptionHandlingUtility.WrapFuncWithExceptionHandling(() =>
            {
                PolicyBuilder policyBuilder = null;
                Assembly currentAssembly = typeof(BasicPollyExceptionHandler).Assembly;
                var pollyTransientFailureExceptionsEmbeddedResourceFilename = currentAssembly.GetManifestResourceNames()[0];
                XDocument xDoc = XDocument.Load(currentAssembly.GetManifestResourceStream(pollyTransientFailureExceptionsEmbeddedResourceFilename));
                _pollyTransientFailureExceptions = XMLUtility.DeSerialize <PollyTransientFailureExceptions>(xDoc.ToString());
                if (_pollyTransientFailureExceptions.TransientFailureExceptions.IsNotNull())
                {
                    _splittedTransientFailureExceptions = _pollyTransientFailureExceptions.TransientFailureExceptions.SelectMany(x => x.CommaSeperatedTransientFailureExceptions.Split(",", StringSplitOptions.RemoveEmptyEntries))
                                                          .Distinct().Select(x => x.Trim().ToLower());
                }

                if (_splittedTransientFailureExceptions.IsNotNullOrEmpty())
                {
                    string firstTransientFailureException = _splittedTransientFailureExceptions.First();
                    string assemblyName = _pollyTransientFailureExceptions.TransientFailureExceptions.SingleOrDefault(x => x.CommaSeperatedTransientFailureExceptions.Contains(firstTransientFailureException)).AssemblyName;
                    Type firstTransientFailureExceptionType = MetaDataUtility.GetType(assemblyName, firstTransientFailureException);
                    Type[] transientFailureExceptionTypesArray = new Type[1];
                    transientFailureExceptionTypesArray[0] = firstTransientFailureExceptionType;
                    policyBuilder = MetaDataUtility.InvokeStaticMethod <Policy, PolicyBuilder>("Handle", transientFailureExceptionTypesArray);

                    IEnumerable <string> transientFailureExceptionsOtherThanTheFirst = _splittedTransientFailureExceptions.Skip(1);
                    if (transientFailureExceptionsOtherThanTheFirst.IsNotNullOrEmpty())
                    {
                        transientFailureExceptionsOtherThanTheFirst.ForEach(x =>
                        {
                            assemblyName = _pollyTransientFailureExceptions.TransientFailureExceptions.SingleOrDefault(y => y.CommaSeperatedTransientFailureExceptions.Contains(x)).AssemblyName;
                            Type transientFailureExceptionTypeForOtherThanTheFirst = MetaDataUtility.GetType(assemblyName, x);
                            Type[] transientFailureExceptionTypesArrayForOtherThanTheFirst = new Type[1];
                            transientFailureExceptionTypesArrayForOtherThanTheFirst[0] = transientFailureExceptionTypeForOtherThanTheFirst;
                            policyBuilder = MetaDataUtility.InvokeInstanceMethod <PolicyBuilder, PolicyBuilder>(policyBuilder, "Or", transientFailureExceptionTypesArrayForOtherThanTheFirst);
                        }
                                                                            );
                    }
                }
                return policyBuilder;
            }, _staticLogger));
        }
コード例 #6
0
ファイル: Test.cs プロジェクト: yanh19930226/beta
        public async Task GetServiceDiscovery()
        {
            var serviceDiscoveryProvider = new ConsulServiceProvider(new Uri("http://127.0.0.1:8500"));

            #region 获取服务节点列表
            //var serviceAList = await serviceDiscoveryProvider.GetServicesAsync("ServiceA");
            //return serviceAList;
            #endregion

            var serviceA = serviceDiscoveryProvider.CreateServiceBuilder(builder =>
            {
                builder.ServiceName = "ServiceA";
                // 指定负载均衡器
                builder.LoadBalancer = TypeLoadBalancer.RoundRobin;
                // 指定Uri方案
                builder.UriScheme = Uri.UriSchemeHttp;
            });
            var httpClient = new HttpClient();
            var policy     = PolicyBuilder.CreatePolly();

            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine($"-------------第{i}次请求-------------");
                policy.Execute(() =>
                {
                    try
                    {
                        var uri = serviceA.BuildAsync("health").Result;
                        System.Diagnostics.Debug.WriteLine($"{DateTime.Now} - 正在调用:{uri}");
                        var content = httpClient.GetStringAsync(uri).Result;
                        System.Diagnostics.Debug.WriteLine($"调用结果:{content}");
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine($"调用异常:{e.GetType()}");
                    }
                });
                Task.Delay(1000).Wait();
            }
        }
コード例 #7
0
        static void Main(string[] args)
        {
            var snowId = new SnowflakeId(1, 1);
            var id     = snowId.NextId();

            var serviceProvider = new ConsulServiceProvider(new Uri("http://127.0.0.1:8500"));
            var myServiceA      = serviceProvider.CreateServiceBuilder(builder =>
            {
                builder.ServiceName = "MyServiceA";
                // 指定负载均衡器
                builder.LoadBalancer = TypeLoadBalancer.RoundRobin;
                // 指定Uri方案
                builder.UriScheme = Uri.UriSchemeHttp;
            });

            var httpClient = new HttpClient();
            var polly      = PolicyBuilder.CreatePolly();

            //
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine($"-------------第{i}次请求-------------");
                polly.Execute(() =>
                {
                    try
                    {
                        var uri = myServiceA.BuildAsync("health").Result;
                        Console.WriteLine($"{DateTime.Now} - 正在调用:{uri}");
                        var content = httpClient.GetStringAsync(uri).Result;
                        Console.WriteLine($"调用结果:{content}");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"调用异常:{e.GetType()}");
                    }
                });
                Task.Delay(1000).Wait();
            }
        }
コード例 #8
0
        public void DuplicateNames()
        {
            var provider = new Mock <IQosPolicyProvider>(MockBehavior.Strict);

            provider
            .SetupGet(p => p.Order)
            .Returns(1);
            provider
            .Setup(p => p.GetPolicies())
            .Returns(new[]
            {
                new QosPolicy("A"),
                new QosPolicy("B"),
                new QosPolicy("A")
            });

            var builder = new PolicyBuilder(
                new[] { provider.Object },
                Enumerable.Empty <IQosPolicyPostConfigure>());

            Assert.Throws <Exception>(() => builder.Build());
        }
コード例 #9
0
        static void Main(string[] args)
        {
            var serviceProvider = new ConsulServiceProvider(new Uri("http://127.0.0.1:8500"));
            var myServiceA      = serviceProvider.CreateServiceBuilder((builder) =>
            {
                builder.ServiceName  = "MyServiceA";
                builder.LoadBalancer = TypeLoadBalancer.RoundRobin;
                builder.UriScheme    = Uri.UriSchemeHttp;
            });


            var policy = PolicyBuilder.CreatePolly();

            var httpClient = new HttpClient();

            for (int i = 0; i < 100; i++)
            {
                policy.Execute(() =>
                {
                    try
                    {
                        var uri = myServiceA.BuildAsync("/health").Result;
                        Console.WriteLine($"{DateTime.Now} - 正在调用:{uri}");
                        var content = httpClient.GetAsync(uri).Result;
                        Console.WriteLine($"调用结果:{content?.StatusCode}");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("业务逻辑异常 ex:" + ex.GetType());
                        throw;
                    }
                });

                Task.Delay(1000).Wait();
            }

            Console.Read();
        }
コード例 #10
0
 public override void Create()
 {
     PolicyBuilder
     .Inbound(builder => builder
              .Base()
              .ValidateJwt(jwtAttr => jwtAttr
                           .HeaderName(HeaderNames.Authorization)
                           .FailedValidationStatusCode(HttpStatusCode.Unauthorized)
                           .FailedValidationMessage("Unauthorized. Access token is missing or invalid.")
                           .Create(),
                           "http://contoso.com/.well-known/openid-configuration",
                           new List <string> {
         "http://contoso.com/"
     }
                           )
              .Create())
     .Backend(builder => builder
              .Base()
              .Create())
     .Outbound(builder => builder
               .Base()
               .Create()
               );
 }
コード例 #11
0
ファイル: AsyncPolicy.cs プロジェクト: zhouweiaccp/Polly
 /// <summary>
 /// Constructs a new instance of a derived <see cref="AsyncPolicy"/> type with the passed <paramref name="policyBuilder"/>.
 /// </summary>
 /// <param name="policyBuilder">A <see cref="PolicyBuilder"/> specifying which exceptions the policy should handle. </param>
 protected AsyncPolicy(PolicyBuilder policyBuilder = null)
     : base(policyBuilder)
 {
 }
コード例 #12
0
 public void IncompletePropertyMappingThrows()
 {
     this.extension.initialize = delegate(ExtensionContext context)
     {
         // can't use the fluent approach, the fluent API doesn't allow for this scenario.
         Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Unity.Fluent.IPropertyAndFinishPolicyBuilding <TestClass, TestClassConfiguration> builder
             = new PolicyBuilder <TestClass, TestClassConfiguration>("foo", this.configuration,
                                                                     c => new TestClass());
         builder.SetProperty(o => o.Prop1);                      // unfinished property
         builder.AddPoliciesToPolicyList(context.Policies);
     };
     container.AddExtension(this.extension);
 }
コード例 #13
0
ファイル: PolicyExpression.cs プロジェクト: pkoronawa/jasper
 /// <summary>
 ///     Specifies an additional type of exception that this policy can handle if found as an InnerException of a regular
 ///     <see cref="Exception" />, or at any level of nesting within an <see cref="AggregateException" />.
 /// </summary>
 /// <typeparam name="TException">The type of the exception to handle.</typeparam>
 /// <returns>The PolicyBuilder instance, for fluent chaining.</returns>
 public PolicyExpression OrInner <TException>() where TException : Exception
 {
     _builder = _builder.OrInner <TException>();
     return(this);
 }
コード例 #14
0
ファイル: PolicyExpression.cs プロジェクト: pkoronawa/jasper
 internal PolicyExpression(RetryPolicyCollection parent, PolicyBuilder <IContinuation> builder)
 {
     _parent  = parent;
     _builder = builder;
 }
コード例 #15
0
 public void DuplicatePolicies()
 {
     var item = new PolicyBuilder <Item>()
                .For(i => i.Method(null), Policy.Handle <FileNotFoundException>().Retry(2))
                .For(i => i.Method(null), Policy.Handle <FileNotFoundException>().Retry(2));
 }
コード例 #16
0
 public void Exception()
 {
     var item = new PolicyBuilder <Item>()
                .For(i => i.Method(null), null);
 }
コード例 #17
0
ファイル: ClientUtils.cs プロジェクト: tan9/openapi-generator
 private static Polly.CircuitBreaker.AsyncCircuitBreakerPolicy <HttpResponseMessage> CircuitBreakerPolicy(
     PolicyBuilder <HttpResponseMessage> builder, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak)
 => builder.CircuitBreakerAsync(handledEventsAllowedBeforeBreaking, durationOfBreak);
コード例 #18
0
 public static Policy <IContinuation> MoveToErrorQueue(this PolicyBuilder <IContinuation> builder)
 {
     return(builder.FallbackAsync((result, context, token) => Task.FromResult <IContinuation>(new MoveToErrorQueue(result.Exception)),
                                  (result, context) => Task.CompletedTask));
 }
コード例 #19
0
 public DurableRetry(ILogger logger, PolicyBuilder policy)
     : base(new RetryPolicies(new LogRetryException(logger).Execute).Get(policy))
 {
 }
コード例 #20
0
 public static AsyncRetryPolicy RetryWithBackoff(this PolicyBuilder policy, int retryCount = 3) =>
 policy.RetryAsync(retryCount, (e, i) => i.ExponentialBackoff(1.Seconds()));
 public Policy GetPolicyAsync(PolicyBuilder policyBuilder)
 {
     return(policyBuilder.RetryAsync(_retryCount, (x, y) => _logger.LogException(new Exception(string.Format("GetPolicyAsync in RetryNTimesPolicy : Tried {0} number of time(s)", y), x))));
 }
コード例 #22
0
 public DiscordRateLimitPolicy(Ratelimiter ratelimiter, PolicyBuilder <HttpResponseMessage>?policyBuilder = null)
     : base(policyBuilder)
 {
     _ratelimiter = ratelimiter;
 }
コード例 #23
0
 public void WithoutPolicy()
 {
     var item = new PolicyBuilder <Item>().Build();
 }
コード例 #24
0
 public Policy GetPolicy(PolicyBuilder policyBuilder)
 {
     return(policyBuilder.Fallback(_fallbackAction, x => _logger.LogError(x, x.Message)));
 }
コード例 #25
0
 public static AsyncRetryPolicy WaitAndRetryAsync(this PolicyBuilder builder, RetryPolicy policy)
 {
     return(builder.WaitAndRetryAsync(policy.MaxAttempts - 1, attempt => policy.GetInterval(attempt)));
 }
コード例 #26
0
 public AsyncPolicy GetPolicyAsync(PolicyBuilder policyBuilder)
 {
     return(policyBuilder.FallbackAsync(_fallbackActionAsync, x => Task.Run(() => _logger.LogError(x, x.Message))));
 }
コード例 #27
0
ファイル: PolicyExpression.cs プロジェクト: pkoronawa/jasper
 /// <summary>
 /// Specifies an additional type of exception that this policy can handle with additional filters on this exception type.
 /// </summary>
 /// <param name="exceptionPredicate">The exception predicate to filter the type of exception this policy can handle.</param>
 /// <returns>The PolicyBuilder instance.</returns>
 public PolicyExpression Or(Func <Exception, bool> exceptionPredicate)
 {
     _builder = _builder.Or(exceptionPredicate);
     return(this);
 }
コード例 #28
0
 public PollyFluentPolicy AddOrType <T>()
     where T : Exception
 {
     p = p.Or <T>();
     return(this);
 }
コード例 #29
0
ファイル: PolicyExpression.cs プロジェクト: pkoronawa/jasper
 /// <summary>
 ///     Specifies an additional type of exception that this policy can handle, with additional filters on this exception type, if
 ///     found as an InnerException of a regular <see cref="Exception" />, or at any level of nesting within an
 ///     <see cref="AggregateException" />.
 /// </summary>
 /// <typeparam name="TException">The type of the exception to handle.</typeparam>
 /// <returns>The PolicyBuilder instance, for fluent chaining.</returns>
 public PolicyExpression OrInner <TException>(Func <TException, bool> exceptionPredicate)
     where TException : Exception
 {
     _builder = _builder.OrInner(exceptionPredicate);
     return(this);
 }
コード例 #30
0
 public PollyFluentPolicy AddType <T>()
     where T : Exception
 {
     p = Policy.Handle <T>();
     return(this);
 }