public async Task <IEnumerable <CustomerDTO> > ListCircuitWithDefault()
 {
     return(circuitPolicy.CircuitState == CircuitState.Closed ?
            await circuitPolicy.ExecuteAsync(async() =>
     {
         return await customerService.List();
     }) :
            default(IEnumerable <CustomerDTO>));
 }
Beispiel #2
0
 public async Task BookAsync(string userId, int accommodationId, BookingDetails details)
 {
     try
     {
         await breaker.ExecuteAsync(() => innerProxy.BookAsync(userId, accommodationId, details));
     }
     catch (HttpOperationException ex)
     {
         throw new RemoteServiceFailedException(ex.StatusCode(), ex);
     }
     catch (BrokenCircuitException ex)
     {
         throw new RemoteServiceFailedException(ex.StatusCode(), ex);
     }
 }
Beispiel #3
0
        public async Task InvokeAsync(HttpContext httpContext)
        {
            try
            {
                if (_policy.CircuitState == CircuitState.Open)
                {
                    throw new ServiceUnavailableException("Service is unavailable.");
                }

                await _policy.ExecuteAsync(async() =>
                {
                    await _next(httpContext);
                });
            }
            catch (TaskCanceledException ex)
            {
                _logger.LogInformation(ex, ex.Message);
                await HandleGlobalExceptionAsync(httpContext, ex);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                await HandleGlobalExceptionAsync(httpContext, ex);
            }
        }
Beispiel #4
0
        private static void _02_斷路器()
        {
            var state = s_asyncCircuitBreakerPolicy.CircuitState;

            try
            {
                Console.WriteLine($"呼叫任務前的狀態:{state}");

                var response = s_asyncCircuitBreakerPolicy.ExecuteAsync(RandomFailResponseOrExceptionAsync)
                               .GetAwaiter()
                               .GetResult();
                var content = response.Content;
                if (content != null)
                {
                    var result = content.ReadAsStringAsync().GetAwaiter().GetResult();
                    Console.WriteLine($"取得服務內容:{result}\r\n"
                                      + $"斷路器狀態:{state}");
                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("斷路器,正常完成");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"錯誤:{e.Message}\r\n"
                                  + $"斷路器狀態:{state}");
            }
            finally
            {
                Console.WriteLine("");
            }
        }
Beispiel #5
0
        private async Task WorkAsync()
        {
            try
            {
                await semaphoreSlim.WaitAsync();

                using (var scope = serviceScopeFactory.CreateScope())
                {
                    InitializePollyIfRequired(scope);
                    await circuitBreaker.ExecuteAsync(async() => await RunInCircuitAsync(scope));
                }
            }
            catch (TaskExecutionFaultException <TIdentifier> criticalException)
            {
                var taskDefinition = criticalException.TaskDefinition;
                if (taskDefinition == null)
                {
                    throw criticalException;
                }
                await faultReporter.ReportAsync(taskDefinition, criticalException.InnerException, false);
            }
            catch { }
            finally
            {
                semaphoreSlim.Release();
            }
        }
Beispiel #6
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, AsyncCircuitBreakerPolicy policy)
 {
     await policy.ExecuteAsync(async() =>
     {
         await action();
     });
 }
Beispiel #7
0
        /// <summary>
        /// GRPC Call with Circuit breaker policy
        /// </summary>
        /// <returns></returns>
        private async Task <long> GetCurrentStoreItems()
        {
            const string url = "https://localhost:7001";

            using GrpcChannel channel = GrpcChannel.ForAddress(url);
            var client  = new InventoryServiceProviderClient(channel);
            var request = new ServiceRequest {
                StoreId = "S001"
            };
            long totalItems = 0L;

            try
            {
                await circuitAsyncBreakerPolicy.ExecuteAsync(async() =>
                {
                    ServiceReplay replay = await client.CountTotalItemsAsync(request);
                    totalItems           = long.Parse(replay.ItemCount);
                });
            }
            catch (RpcException rEx)
            {
                Debug.WriteLine($"Grpc Exception:{rEx.Message}");
                await Task.Delay(1000);
            }

            return(totalItems);
        }
Beispiel #8
0
        public async Task <ActionResult <NumberIsPrimeDto> > CheckNumberIsPrime(CheckNumberDto checkNumberDto)
        {
            _loggingManager.LogInformation($"CheckNumberIsPrime endpoint started. number: {checkNumberDto.Number}");

            try
            {
                bool isPrimeResult = false;

                await _circuitBreakerPolicy.ExecuteAsync(async() =>
                {
                    var cancelTokenSource = new CancellationTokenSource();
                    cancelTokenSource.CancelAfter(TimeSpan.FromSeconds(_policyConfiguration.TimoutInMinutes));

                    var numberIsPrimeResult = await _mediator.Send(
                        new CheckNumberIsPrimeCommand
                    {
                        Number = checkNumberDto.Number
                    }, cancelTokenSource.Token);

                    isPrimeResult = numberIsPrimeResult.IsPrime;
                });

                return(Ok(new NumberIsPrimeDto
                {
                    IsPrime = isPrimeResult
                }));
            }
            catch (TaskCanceledException taskCanceledException)
            {
                _loggingManager.LogError(taskCanceledException.Message);

                return(Problem(
                           title: "The computation runs too long. Please check back later or use a HATEOAS enabled endpoint.",
                           detail: taskCanceledException.Message,
                           statusCode: (int)HttpStatusCode.RequestTimeout));
            }
            catch (Exception exception)
            {
                _loggingManager.LogError(exception.Message);

                return(Problem(
                           title: "Unexpected error. Please contact support.",
                           detail: exception.Message,
                           statusCode: (int)HttpStatusCode.InternalServerError));
            }
        }
Beispiel #9
0
        public async Task <IActionResult> Get(int id)
        {
            string requestEndpoint = $"NotStableAmazonInventory/{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()));
        }
Beispiel #10
0
        static void CircuitBreakerPolicyWith2ConsecutiveCallsWithBlockingThread()
        {
            AsyncCircuitBreakerPolicy <string> asyncCircuitBreakerPolicy = Policy <string>
                                                                           .Handle <InvalidOperationException>()
                                                                           .CircuitBreakerAsync(1, TimeSpan.FromSeconds(10), //can handle 1 event only
                                                                                                (exception, timespan) =>
            {
                Console.WriteLine("On Break!");
            }, () =>
            {
                Console.WriteLine("On Reset!");
            });

            string data = "Hello World";

            Console.WriteLine($"[CircuitBreaker] Original string: {data}");
            try
            {
                string result = asyncCircuitBreakerPolicy.ExecuteAsync(async() => await ReverseString(data)).Result;
                Console.WriteLine($"[CircuitBreaker] Reversed string 1: {result}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Cannot handle InvalidOperationException!");
                Console.WriteLine("Error detail:");
                Console.WriteLine(ex.ToString());
            }

            Thread.Sleep(10000); //wait around 10 secs

            try
            {
                string result2 = asyncCircuitBreakerPolicy.ExecuteAsync(async() => await ReverseString(data, true)).Result;
                Console.WriteLine($"[CircuitBreaker] Reversed string 2: {result2}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Cannot handle InvalidOperationException!");
                Console.WriteLine("Error detail:");
                Console.WriteLine(ex.ToString());
            }
        }
Beispiel #11
0
 public async Task <IEnumerable <ProductModel> > GetProductsDataAsync()
 {
     try
     {
         Console.WriteLine(circuitBreakerPolicy.CircuitState);
         return(await circuitBreakerPolicy?.ExecuteAsync <IEnumerable <ProductModel> >(async() => await apiDemo1Service.GetProductsDataAsync()));
     }
     catch
     {
         throw;
     }
 }
Beispiel #12
0
        public async Task <NotificationResponse> SendEmail(EmailMessage message)
        {
            var notificationRespose = new NotificationResponse
            {
                statusCode = "1",
                message    = "Email sent Error"
            };

            try
            {
                Console.WriteLine($"Estado del circuito: {_circuitBreakerPolicy.CircuitState}");
                await _circuitBreakerPolicy.ExecuteAsync(async() =>
                {
                    try
                    {
                        var mimeMessage = await CreateMimeMessageFromEmailMessage(message);

                        await _smtpClient.ConnectAsync(_notificationMetadata.SmtpServer,
                                                       _notificationMetadata.Port, false);
                        await _smtpClient.AuthenticateAsync(_notificationMetadata.UserName,
                                                            _notificationMetadata.Password);

                        await _smtpClient.SendAsync(mimeMessage);

                        notificationRespose.statusCode = "0";
                        notificationRespose.message    = "Email sent successfully";
                    }
                    finally
                    {
                        await _smtpClient.DisconnectAsync(true);
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Erro al enviar correo: {ex.Message}");
            }
            finally
            {
                var newNotification = new ApplicationCore.DTO.Notification
                {
                    Message          = message.Content,
                    status           = notificationRespose.statusCode,
                    Type             = "E",
                    Reciever         = message.Reciever,
                    DateNotification = DateTime.UtcNow.ToLocalTime()
                };

                await persistNotification(newNotification);
            }

            return(notificationRespose);
        }
Beispiel #13
0
        public async Task <IActionResult> Get(int id)
        {
            string requestEndpoint = $"samples/circuit-breaker/inventory/{id}";

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

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

                return(Ok(itemsInStock));
            }

            if (response.Content != null)
            {
                return(StatusCode((int)response.StatusCode, response.Content.ReadAsStringAsync()));
            }

            return(StatusCode((int)response.StatusCode));
        }
Beispiel #14
0
 public async Task <string> GetGoodbyeMessage()
 {
     try
     {
         Console.WriteLine($"Circuit State: {_circuitBreakerPolicy.CircuitState}");
         return(await _circuitBreakerPolicy.ExecuteAsync <string>(async() =>
         {
             return await _messageRepository.GetGoodbyeMessage();
         }));
     }
     catch (Exception ex)
     {
         return(ex.Message);
     }
 }
Beispiel #15
0
        public async Task <IActionResult> GetProduct_Alt(int productId)
        {
            var httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://localhost:44363/")
            };

            // Circuit Breaker
            // var response = await _circuitBreakerPolicy.ExecuteAsync(() => httpClient.GetAsync($"api/inventories/{productId}"));

            // Advanced circuit breaker
            var response = await _advancedCircuitBreakerPolicy.ExecuteAsync(() => httpClient.GetAsync($"api/inventories/{productId}"));

            var result = await response.Content.ReadAsStringAsync();

            return(new OkObjectResult(result));
        }
        static async Task Main(string[] args)
        {
            _circuitBreakerPolicy = Policy.HandleResult <HttpResponseMessage>(r => !r.IsSuccessStatusCode)
                                    .CircuitBreakerAsync(1, TimeSpan.FromSeconds(10), OnBreak, OnReset, OnHalfOpen);

            var apiClient = new HttpClient();
            int count     = 0;

            while (true)
            {
                count++;
                Console.WriteLine($"Start calling to web API");
                Console.WriteLine("\n");
                Console.WriteLine("------------------------------------------------------------------------------------");

                //start calling web API
                var apiResponse = new HttpResponseMessage();

                try
                {
                    apiResponse = await _circuitBreakerPolicy.ExecuteAsync(
                        () => apiClient.GetAsync("https://localhost:5001/api/v1/quote/test", HttpCompletionOption.ResponseContentRead));

                    var json = await apiResponse.Content.ReadAsStringAsync();

                    //End

                    Console.WriteLine($"Http status code : {apiResponse.StatusCode}");
                    Console.WriteLine("\n");
                    Console.WriteLine($"Response: {json}");
                    Console.WriteLine("\n");
                    Console.WriteLine($"{count}. End calling to web API");
                    Console.WriteLine("\n");
                    Console.WriteLine("------------------------------------------------------------------------------------");
                    Console.WriteLine("Type any key and press ENTER to make new call to API");
                    Console.WriteLine("------------------------------------------------------------------------------------");
                    Console.ReadLine();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.ReadLine();
                }
            }
        }
Beispiel #17
0
 public async Task Protect(Func <Task> action)
 {
     try
     {
         await _policyCircuitBreaker.ExecuteAsync(action);
     }
     catch (BrokenCircuitException e)
     {
         await _messagingService.SendLogMessage($"Exception: '{e.Message}'.");
     }
     catch (RpcResponseException e)
     {
         await _messagingService.SendLogMessage($"Exception: '{e.Message}'.");
     }
     catch (RpcClientUnknownException e)
     {
         await _messagingService.SendLogMessage($"Exception: '{e.Message}'.");
     }
 }
        static async Task Main(string[] args)
        {
            var apiClient = new HttpClient();
            int i         = 0;

            while (true)
            {
                i++;
                Console.WriteLine($"{i}. Start calling to Web API");
                Console.WriteLine("\n");
                Console.WriteLine("-------------------------------------------------------------------------------------------");
                // Start calling to WebAPI
                var apiResponse = new HttpResponseMessage();
                try
                {
                    apiResponse = await _circuitBreakerPolicy.ExecuteAsync(
                        () => apiClient.GetAsync("https://localhost:5001/weatherforecast", HttpCompletionOption.ResponseContentRead)
                        );

                    var json = await apiResponse.Content.ReadAsStringAsync();

                    // End calling to WebAPI

                    Console.WriteLine($"Http Status Code: {apiResponse.StatusCode}");
                    Console.WriteLine("\n");
                    Console.WriteLine($"Response: {json}");
                    Console.WriteLine("\n");
                    Console.WriteLine($"{i}. End calling to Web API");
                    Console.WriteLine("\n");
                    Console.WriteLine("-------------------------------------------------------------------------------------------");
                    Console.WriteLine("Type any key and press Enter to make new calling to Web API");
                    Console.WriteLine("-------------------------------------------------------------------------------------------");
                    Console.ReadLine();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.ReadLine();
                }
            }
        }
Beispiel #19
0
        public async Task <TimeCard> SendTimeCardMessage(string timeCard)
        {
            var stringContent = new StringContent(timeCard, UnicodeEncoding.UTF8, "application/json");


            HttpClient          client   = _httpClientFactory.CreateClient();
            var                 uri      = "https://YourUriGoesHere";
            HttpResponseMessage response = await _retryPolicy.ExecuteAsync(
                () => _circuitBreaker.ExecuteAsync(() => client.PostAsync(requestUri: uri, stringContent)
                                                   ));

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return(null);
            }

            var resultString = await response.Content.ReadAsStringAsync();

            return(JsonSerializer.Deserialize <TimeCard>(resultString));



            ////Excute Retry Policy Only
            //return await _retryPolicy.ExecuteAsync(async () =>
            //{
            //    var uri = "https://YourUriGoesHere";

            //    //Post to api with client
            //    HttpResponseMessage result = await client.PostAsync(requestUri: uri, stringContent);

            //    if (result.StatusCode != System.Net.HttpStatusCode.OK)
            //    {
            //        return null;
            //    }

            //    var resultString = await result.Content.ReadAsStringAsync();
            //    return JsonSerializer.Deserialize<TimeCard>(resultString);

            // });
        }
Beispiel #20
0
 private async Task <HttpResponseMessage> HttpInvoker(Func <Task <HttpResponseMessage> > operation)
 {
     return(await _retryPolly.ExecuteAsync(() => _circuitBreakerPolicy.ExecuteAsync(operation)));
 }
Beispiel #21
0
 public Task <string> GetStringAsync(string cacheKey)
 {
     return(_cachingPolicy.ExecuteAsync(() => _cache.GetStringAsync(cacheKey)));
 }
        public async Task <IActionResult> Index()
        {
            HttpClient client = new HttpClient();
            var        result = await _fallbackPolicy.ExecuteAsync(() => _retryPolicy.ExecuteAsync(()
                                                                                                   => _circuitBreakerPolicy.ExecuteAsync(() => client.GetAsync(_baseUrl))));

            var str = await result.Content.ReadAsStringAsync();

            var obj = JsonConvert.DeserializeObject <MessageClient>(str);

            return(Ok(obj));
        }
Beispiel #23
0
 public virtual async Task <TResult> ExecuteAsync(Func <Task <TResult> > action)
 {
     return(await _retryPolicy.ExecuteAsync(async() =>
                                            await _breaker.ExecuteAsync(async() => await action.Invoke())));
 }