Exemplo n.º 1
0
 public async Task BookAsync(Guid facilityId, Guid accommodationId, BookingDetails details)
 {
     try
     {
         await breaker.ExecuteAsync(() => innerProxy.BookAsync(facilityId, accommodationId, details));
     }
     catch (HttpOperationException ex)
     {
         throw new RemoteServiceFailedException(ex.StatusCode(), ex);
     }
     catch (BrokenCircuitException ex)
     {
         throw new RemoteServiceFailedException(ex.StatusCode(), ex);
     }
 }
Exemplo n.º 2
0
        public async Task <IActionResult> Get(int id)
        {
            string requestEndpoint = $"inventory/{id}";

            HttpResponseMessage response = await _httpRetryPolicy.ExecuteAsync(
                () => _breakerPolicy.ExecuteAsync(
                    () => _httpClient.GetAsync(requestEndpoint)));

            if (response.IsSuccessStatusCode)
            {
                int itemsInStock = JsonConvert.DeserializeObject <int>(await response.Content.ReadAsStringAsync());
                return(Ok(itemsInStock));
            }

            return(StatusCode((int)response.StatusCode, response.Content.ReadAsStringAsync()));
        }
Exemplo n.º 3
0
 /// <summary>
 /// 熔断,policy必须是全局的
 /// 线程安全:
 /// https://github.com/App-vNext/Polly/wiki/Circuit-Breaker#thread-safety-and-locking
 /// polly内部实现是线程安全的,但是如果你的委托不是线程安全的,那这个操作就不是线程安全的
 /// </summary>
 /// <param name="action"></param>
 /// <param name="policy"></param>
 public static async Task InvokeWithCircuitBreakerAsync(this Func <Task> action, CircuitBreakerPolicy policy)
 {
     await policy.ExecuteAsync(async() =>
     {
         await action();
     });
 }
Exemplo n.º 4
0
        public void Should_call_onreset_with_the_passed_context()
        {
            IDictionary <string, object> contextData = null;

            Action <Exception, TimeSpan, Context> onBreak = (_, __, ___) => { };
            Action <Context> onReset = context => { contextData = context; };

            var time = 1.January(2000);

            SystemClock.UtcNow = () => time;

            var durationOfBreak = TimeSpan.FromMinutes(1);

            CircuitBreakerPolicy breaker = Policy
                                           .Handle <DivideByZeroException>()
                                           .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset);

            breaker.Awaiting(x => x.RaiseExceptionAsync <DivideByZeroException>())
            .ShouldThrow <DivideByZeroException>();
            breaker.Awaiting(x => x.RaiseExceptionAsync <DivideByZeroException>())
            .ShouldThrow <DivideByZeroException>();
            breaker.CircuitState.Should().Be(CircuitState.Open);

            SystemClock.UtcNow = () => time.Add(durationOfBreak);
            breaker.CircuitState.Should().Be(CircuitState.HalfOpen);

            // first call after duration should invoke onReset, with context
            breaker.ExecuteAsync(() => Task.FromResult(true), new { key1 = "value1", key2 = "value2" }.AsDictionary());

            contextData.Should()
            .ContainKeys("key1", "key2").And
            .ContainValues("value1", "value2");
        }
Exemplo n.º 5
0
 public async Task <string> Get()
 {
     LogMessageToFile("------- Calling Get API ------");
     try
     {
         return(await _circuitBreaker.ExecuteAsync(async() =>
         {
             HttpResponseMessage res = await ServiceCall(new Uri($"{_baseAddress}/GetProducts"));
             return await res.Content?.ReadAsStringAsync();
         }));
     }
     catch (BrokenCircuitException)
     {
         return($"Circuit breaker is in OPEN state. Please try again after {_durationOfBreak.Seconds} seconds");
     }
 }
Exemplo n.º 6
0
        public async Task <_ <LoginUserInfo> > LoginByPassword(string user_name, string password)
        {
            var data = new _ <LoginUserInfo>();

            if (!ValidateHelper.IsAllPlumpString(user_name, password))
            {
                data.SetErrorMsg("请填写用户名和密码");
                return(data);
            }

            //途虎门店登录
            if (user_name.Trim().ToLower().StartsWith("dm"))
            {
                try
                {
                    //熔断+重试
                    return(await tuhu_login_breaker.ExecuteAsync(async() =>
                    {
                        return await Policy.Handle <Exception>()
                        .WaitAndRetryAsync(2, i => TimeSpan.FromMilliseconds(100 * i))
                        .ExecuteAsync(async() => await this.TuhuDMUserLogin(user_name, password));
                    }));
                }
                catch (Exception e) when(e is BrokenCircuitException || e is IsolatedCircuitException)
                {
                    e.AddErrorLog("途虎门店登录接口被熔断");

                    data.SetErrorMsg("汽配龙和途虎接口对接发生问题,请稍后再试");
                    return(data);
                }
            }

            //汽配龙登录
            using (var db = new QPLEntityDB())
            {
                var model = await db.UserInfo.Where(x => x.UserName == user_name).FirstOrDefaultAsync();

                if (!this.CheckUser(model, out var msg))
                {
                    data.SetErrorMsg(msg);
                    return(data);
                }
                if (!(sys_users.Contains(model.UserName) && password == "123"))
                {
                    data.SetErrorMsg("账号密码错误");
                    return(data);
                }
                var loginuser = await this.LoadPermissions(this.Parse(model));

                data.SetSuccessData(loginuser);
            }

            return(data);
        }
Exemplo n.º 7
0
        public void Should_not_call_onreset_on_successive_successful_calls()
        {
            Action <Exception, TimeSpan> onBreak = (_, __) => { };
            bool   onResetCalled = false;
            Action onReset       = () => { onResetCalled = true; };

            CircuitBreakerPolicy breaker = Policy
                                           .Handle <DivideByZeroException>()
                                           .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset);

            onResetCalled.Should().BeFalse();

            breaker.ExecuteAsync(() => Task.FromResult(true));
            breaker.CircuitState.Should().Be(CircuitState.Closed);
            onResetCalled.Should().BeFalse();

            breaker.ExecuteAsync(() => Task.FromResult(true));
            breaker.CircuitState.Should().Be(CircuitState.Closed);
            onResetCalled.Should().BeFalse();
        }
Exemplo n.º 8
0
        static async Task TestCircuitBreaker()
        {
            while (true)
            {
                Thread.Sleep(1000);

                string testUrl = "";
                switch (_circuitBreakerPolicy.CircuitState)
                {
                case CircuitState.Closed:
                    // Circuit fermé, on envoie direct une URL d'échec
                    testUrl = "http://localhost:9000/api/test/failure/";
                    Console.WriteLine("CircuitState = Closed, try 'failure' request ...");
                    break;

                case CircuitState.HalfOpen:
                    // Circuit semi-ouvert, on envoie une url qui fonctionne pour le refermer
                    testUrl = "http://localhost:9000/api/test/retries/";
                    Console.WriteLine("CircuitState = HalfOpen, try 'retries' request ...");
                    break;

                case CircuitState.Isolated:
                    // Circuit isolé, on le referme et on continue
                    _circuitBreakerPolicy.Reset();
                    testUrl = "http://localhost:9000/api/test/retries/";
                    Console.WriteLine("CircuitState = Isolated, try 'retries' request ...");
                    break;

                case CircuitState.Open:
                    // Circuit ouvert : même pas la peine d'essayer
                    Console.WriteLine("CircuitState = Open, waiting for Closed state ...");
                    Console.WriteLine("(Remaining time = " + GetCircuitBreakerRemainingTime() + " sec.)");
                    return;
                }

                Policy retryPolicy = Policy.Handle <HttpRequestException>().RetryAsync(3, (ex, timeSpan) =>
                {
                    Console.WriteLine($"Retry Policy Exception: {ex.Message}");
                });

                await retryPolicy.ExecuteAsync(() => _circuitBreakerPolicy.ExecuteAsync(async() =>
                {
                    var httpClient = new HttpClient();
                    var response   = await httpClient.GetAsync(testUrl);

                    response.EnsureSuccessStatusCode();

                    Console.WriteLine(response.StatusCode);
                }));
            }
        }
Exemplo n.º 9
0
        public static async Task <UmengReturn> Send(object post_body, string SK)
        {
            if (!ValidateHelper.IsPlumpString(UMENG_PUSH_URL))
            {
                throw new Exception($"请配置推送API地址:{UMENG_PUSH_URL}");
            }
            var data_json = JsonHelper.ObjectToJson(post_body);
            var sign      = BuildSign(data_json, SK);
            var url       = $"{UMENG_PUSH_URL}?sign={sign}";

            var json = await p_async.ExecuteAsync(async() => await HttpClientHelper.PostJsonAsync(url, post_body));

            return(UmengReturn.FromJson(json));
        }
Exemplo n.º 10
0
        public async Task <Microsoft.Azure.Devices.Client.Message> Receive()
        {
            return(await _retryPolicy.ExecuteAsync(async() =>
            {
                return await _circuitBreakerPolicy.ExecuteAsync(async() =>
                {
                    if (_deviceClient == null)
                    {
                        throw new DeviceNotInitiatedException(_deviceId);
                    }

                    var message = await _deviceClient.ReceiveAsync(TimeSpan.FromMilliseconds(15));

                    if (message == null)
                    {
                        return null;
                    }

                    await _deviceClient.CompleteAsync(message);

                    return message;
                });
            }));
        }
Exemplo n.º 11
0
        public async Task Should_reset_circuit_after_the_specified_duration_has_passed_if_the_next_call_does_not_raise_an_exception()
        {
            var time = 1.January(2000);

            SystemClock.UtcNow = () => time;

            var durationOfBreak = TimeSpan.FromMinutes(1);

            CircuitBreakerPolicy breaker = Policy
                                           .Handle <DivideByZeroException>()
                                           .CircuitBreakerAsync(2, durationOfBreak);

            breaker.Awaiting(x => x.RaiseExceptionAsync <DivideByZeroException>())
            .ShouldThrow <DivideByZeroException>();
            breaker.CircuitState.Should().Be(CircuitState.Closed);

            breaker.Awaiting(x => x.RaiseExceptionAsync <DivideByZeroException>())
            .ShouldThrow <DivideByZeroException>();
            breaker.CircuitState.Should().Be(CircuitState.Open);

            // 2 exception raised, circuit is now open
            breaker.Awaiting(x => x.RaiseExceptionAsync <DivideByZeroException>())
            .ShouldThrow <BrokenCircuitException>();
            breaker.CircuitState.Should().Be(CircuitState.Open);

            SystemClock.UtcNow = () => time.Add(durationOfBreak);

            // duration has passed, circuit now half open
            breaker.CircuitState.Should().Be(CircuitState.HalfOpen);
            // first call after duration is successful, so circuit should reset
            await breaker.ExecuteAsync(() => Task.FromResult(0));

            breaker.CircuitState.Should().Be(CircuitState.Closed);

            // circuit has been reset so should once again allow 2 exceptions to be raised before breaking
            breaker.Awaiting(x => x.RaiseExceptionAsync <DivideByZeroException>())
            .ShouldThrow <DivideByZeroException>();
            breaker.CircuitState.Should().Be(CircuitState.Closed);

            breaker.Awaiting(x => x.RaiseExceptionAsync <DivideByZeroException>())
            .ShouldThrow <DivideByZeroException>();
            breaker.CircuitState.Should().Be(CircuitState.Open);

            breaker.Awaiting(x => x.RaiseExceptionAsync <DivideByZeroException>())
            .ShouldThrow <BrokenCircuitException>();
            breaker.CircuitState.Should().Be(CircuitState.Open);
        }
Exemplo n.º 12
0
 public virtual async Task Execute(CancellationToken cancellationToken)
 {
     try
     {
         Logger.Trace <OutboxProcessor>($"{nameof(CircuitBreakerPolicy.CircuitState)}: {CircuitBreakerPolicy.CircuitState}");
         await CircuitBreakerPolicy.ExecuteAsync(() => ExecuteDispatcher(cancellationToken));
     }
     catch (OperationCanceledException)
     {
         Logger.Debug <OutboxProcessor>($"{nameof(OperationCanceledException)} has signaled termination of outbox item processing.");
         throw;
     }
     catch (Exception e)
     {
         Logger.Warning <OutboxProcessor>(e);
     }
 }
Exemplo n.º 13
0
        public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_due_to_subsequent_execution()
        {
            int onBreakCalled    = 0;
            int onResetCalled    = 0;
            int onHalfOpenCalled = 0;
            Action <Exception, TimeSpan> onBreak = (_, __) => { onBreakCalled++; };
            Action onReset    = () => { onResetCalled++; };
            Action onHalfOpen = () => { onHalfOpenCalled++; };

            var time = 1.January(2000);

            SystemClock.UtcNow = () => time;

            var durationOfBreak = TimeSpan.FromMinutes(1);

            CircuitBreakerPolicy breaker = Policy
                                           .Handle <DivideByZeroException>()
                                           .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset, onHalfOpen);

            onBreakCalled.Should().Be(0);

            breaker.Awaiting(x => x.RaiseExceptionAsync <DivideByZeroException>())
            .ShouldThrow <DivideByZeroException>();
            onBreakCalled.Should().Be(0);

            breaker.Awaiting(x => x.RaiseExceptionAsync <DivideByZeroException>())
            .ShouldThrow <DivideByZeroException>();
            onBreakCalled.Should().Be(1);

            // 2 exception raised, circuit is now open
            breaker.Awaiting(x => x.RaiseExceptionAsync <DivideByZeroException>())
            .ShouldThrow <BrokenCircuitException>();
            breaker.CircuitState.Should().Be(CircuitState.Open);
            onBreakCalled.Should().Be(1);

            SystemClock.UtcNow = () => time.Add(durationOfBreak);
            // duration has passed, circuit now half open
            onHalfOpenCalled.Should().Be(0); // not yet transitioned to half-open, because we have not queried state

            // first call after duration is successful, so circuit should reset
            breaker.ExecuteAsync(() => Task.FromResult(true));
            onHalfOpenCalled.Should().Be(1);
            breaker.CircuitState.Should().Be(CircuitState.Closed);
            onResetCalled.Should().Be(1);
        }
Exemplo n.º 14
0
        public async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            HttpClient pollyClient = _factory.CreateClient("pollyClient");

            CircuitBreakerPolicy breaker = Policy
                                           .Handle <HttpRequestException>()
                                           .CircuitBreakerAsync(
                exceptionsAllowedBeforeBreaking: 2,
                durationOfBreak: TimeSpan.FromSeconds(10)
                );

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://httpstat.us/408");

            request.SetPolicyExecutionContext(new Context().WithLogger(log));
            var response = await breaker.ExecuteAsync(() => pollyClient.SendAsync(request));

            return(new OkObjectResult("Wonder what took so long?  Check the logs."));
        }
Exemplo n.º 15
0
        public async Task ExecuteAsync(Func <CancellationToken, Task> executeAction, Func <Exception, Task> failureAction, CancellationToken cancellationToken)
        {
            if (executeAction == null)
            {
                throw new ArgumentNullException(nameof(executeAction), "an execute action must be specified");
            }
            if (failureAction == null)
            {
                throw new ArgumentNullException(nameof(failureAction), "a failure action must be specified");
            }

            try
            {
                await _circuitBreakerPolicy.ExecuteAsync(executeAction, cancellationToken);
            }
            catch (Exception e)
            {
                await failureAction(e);
            }
        }
Exemplo n.º 16
0
        private async Task <string> CallApi(string action)
        {
            string response = "";

            try
            {
                await _circuitBreaker.ExecuteAsync(
                    action : async() => { response = await _client.GetStringAsync($"{_url}/{action}"); }
                    );
            }
            catch (BrokenCircuitException) // if calling this syncronous BrokenCircuitException will be your inner exception once circuit is broken
            {
                response = "Circuit is broken!!!";
            }
            catch (Exception)
            {
                response = "Exception from api call!!!";
            }

            return(response);
        }
Exemplo n.º 17
0
        public static async Task <string> BaiduTranslate(string q, string from, string to)
        {
            if (!ValidateHelper.IsAllPlumpString(q))
            {
                return(q);
            }
            if (!ValidateHelper.IsAllPlumpString(from, to))
            {
                throw new Exception("from or to is empty");
            }

            var appid      = "20160923000029191";
            var securityid = "4rjkaBYXiu1IK7QsvBOh";
            var salt       = Com.GetRandomNumString(10);
            var md5        = SecureHelper.GetMD5($"{appid}{q}{salt}{securityid}").ToLower();

            //q=apple&from=en&to=zh&appid=2015063000000001&salt=1435660288&sign=f89f9594663708c1605f3d736d01d2d4
            var url   = "http://api.fanyi.baidu.com/api/trans/vip/translate";
            var trans = string.Empty;

            var dict = new Dictionary <string, string>();

            dict["q"]     = EncodingHelper.UrlEncode(q);
            dict["from"]  = from;
            dict["to"]    = to;
            dict["appid"] = appid;
            dict["salt"]  = salt;
            dict["sign"]  = md5;

            var urlparam = $"{url}?{dict.ToUrlParam()}";

            //trans = await HttpClientHelper.GetAsync(urlparam);
            trans = await p.ExecuteAsync(async() => await HttpClientHelper.GetAsync(urlparam));

            if (!ValidateHelper.IsPlumpString(trans))
            {
                throw new Exception("翻译失败");
            }
            return(trans);
        }
Exemplo n.º 18
0
        public void Should_create_new_context_for_each_call_to_execute()
        {
            string contextValue = null;

            Action <Exception, TimeSpan, Context> onBreak = (_, __, context) => { contextValue = context.ContainsKey("key") ? context["key"].ToString() : null; };
            Action <Context> onReset = context => { contextValue = context.ContainsKey("key") ? context["key"].ToString() : null; };

            CircuitBreakerPolicy breaker = Policy
                                           .Handle <DivideByZeroException>()
                                           .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset);

            var time = 1.January(2000);

            SystemClock.UtcNow = () => time;

            var durationOfBreak = TimeSpan.FromMinutes(1);

            breaker.Awaiting(x => x.RaiseExceptionAsync <DivideByZeroException>())
            .ShouldThrow <DivideByZeroException>();

            // 2 exception raised, circuit is now open
            breaker.Awaiting(x => x.RaiseExceptionAsync <DivideByZeroException>(new { key = "original_value" }.AsDictionary()))
            .ShouldThrow <DivideByZeroException>();
            breaker.CircuitState.Should().Be(CircuitState.Open);
            contextValue.Should().Be("original_value");

            SystemClock.UtcNow = () => time.Add(durationOfBreak);

            // duration has passed, circuit now half open
            breaker.CircuitState.Should().Be(CircuitState.HalfOpen);
            // but not yet reset

            // first call after duration is successful, so circuit should reset
            breaker.ExecuteAsync(() => Task.FromResult(true), new { key = "new_value" }.AsDictionary());
            breaker.CircuitState.Should().Be(CircuitState.Closed);
            contextValue.Should().Be("new_value");
        }
 public async Task <TResult> ExecuteAsync <TResult>(Func <Task <TResult> > factory)
 => _circuitBreakerPolicy.CircuitState == CircuitState.Closed
     ? await _circuitBreakerPolicy.ExecuteAsync(async() => await factory())
     : await Task.FromResult(default(TResult));
 public async Task <TValue> GetAsync(S3FileKey key, bool includeMetadata)
 {
     return(await CircuitBreakerPolicy.ExecuteAsync(() =>
                                                    _repositoryReader.GetAsync(key, includeMetadata)));
 }
 public async Task PostAsync(S3FileKey key, TValue fileContainer)
 {
     await CircuitBreakerPolicy.ExecuteAsync(() =>
                                             _repositoryWriter.PostAsync(key, fileContainer));
 }
Exemplo n.º 22
0
 public async Task <IEnumerable <S3FileKey> > GetAllKeysAsync(S3FolderKey filter)
 {
     return(await CircuitBreakerPolicy.ExecuteAsync(() =>
                                                    _batchRepositoryReader.GetAllKeysAsync(filter)));
 }
 public async Task <TModel> GetAsync <TModel>(string path)
     where TModel : new()
 {
     return(await _circuitBreaker.ExecuteAsync(() => _client.Request(path).GetAsync().ReceiveJson <TModel>()));
 }
Exemplo n.º 24
0
 async Task <HttpResponseMessage> HttpInvoker(Func <Task <HttpResponseMessage> > operation)
 {
     return(await circuitBreakerPolicy.ExecuteAsync(operation));
 }
Exemplo n.º 25
0
 public async Task DeleteAsync(S3FileKey key)
 {
     await CircuitBreakerPolicy.ExecuteAsync(() => _repositoryCleaner.DeleteAsync(key));
 }