Circuit breaker in. NET Core

Source: Internet
Author: User

Talk about the simple application of circuit breaker in. NET Core

Objective
Because of the prevalence of micro-services, many companies will be the original fine granularity than the larger service split into a number of small services, so that each small service to do their own thing.

After splitting, you will not be able to avoid the mutual call between the service problem! If the call is not handled well, it is possible to cause the entire system paralysis, such as some of the basic services have failed, then the use of these basic services are to do a certain amount of processing, can not let them appear large area of paralysis!!!

Under normal circumstances the solution is to fuse the service, not because the provider has problems and let the caller also obsolete.

Fuse generally refers to the software system, due to some reasons to make the service overload phenomenon, in order to prevent the entire system failure, thereby adopting a protective measure.

For this problem, Steeltoe's circuit breaker is a good choice. The sample code for this article is also based on it.

Steeltoe's Circuit breaker
What is Steeltoe? Steeltoe can be said to be a solution for building microservices. Specific access to it's official website:

http://steeltoe.io/

Return to the point, first look at the official description of circuit breaker:

What does when is a service depend on stops responding? Circuit breakers enable bypass a failing service, allowing it time to recover, and preventing your the users from Seein G Nasty error messages. Steeltoe includes a. NET implementation of Netflix Hystrix, a proven circuit breaker implementation with rich metrics and Monitoring features.

It is not hard to find out that circuit breaker can help us deal with the failure of the service very well. It also contains the. NET (Core) Implementation of the Netflix Hystrix.

With regard to the fusing mechanism, there is a very classic diagram (which takes the official documents directly), and the core depicts the relationship between the three states.

Having said that, let's look at a simple example to get a little deeper understanding.

Note: Service discovery and Service registration are not the focus of this article, so the Steeltoe features are not used here.

Simple example
Define a simple order service, the service is simple, a return directly to the corresponding order number interface, here with the default ASP. NET Core Web API project to make adjustments.

[Route ("Api/[controller]")]
public class Valuescontroller:controller
{
GET api/values/123
[HttpGet ("{ID}")]
public string Get (string id)
{
return $ "order-{id}";
}
}
Another new service to call the above order service.

Let go of the fuse-related, define a service interface and implementation for accessing order services.

public interface IOrderService
{
Task Getorderdetailsasync (string orderId);
}

public class Orderservice:iorderservice
{
Public async Task Getorderdetailsasync (String orderId)
{
using (HttpClient client = new HttpClient ())
{
return await client. Getstringasync ($ "Http://localhost:9999/api/values/{orderid}");
}
}
}
The simple thing is to initiate an HTTP request to the order service and take a look at the returned results.

Ignoring the fuse, it is now possible to get the results through this orderservice.

[HttpGet]
Public async Task Get ([fromservices] Services.iorderservice service, String id = "0")
{
return await service. Getorderdetailsasync (ID);
}
The results are as follows:

This is the most ideal situation! What happens if we stop the order service?

Very embarrassing, the caller of this order service is also obsolete.

Of course, Try-catch can also help us deal with this embarrassing problem, but this is not the result we want!

Let's take a look at how to deal with this problem slightly gracefully after introducing circuit breaker.

Define a Getorderdetailshystrixcommand and let it inherit Hystrixcommand.

public class Getorderdetailshystrixcommand:hystrixcommand
{
Private ReadOnly IOrderService _service;
Private readonly ILogger _logger;
private string _orderid;

public GetOrderDetailsHystrixCommand(    IHystrixCommandOptions options,    IOrderService service,    ILogger<GetOrderDetailsHystrixCommand> logger    ) : base(options){    this._service = service;    this._logger = logger;    this.IsFallbackUserDefined = true;}public async Task<string> GetOrderDetailsAsync(string orderId){    _orderId = orderId;    return await ExecuteAsync();}protected override async Task<string> RunAsync(){    var result = await _service.GetOrderDetailsAsync(_orderId);    _logger.LogInformation("Get the result : {0}", result);    return result;}protected override async Task<string> RunFallbackAsync(){    //断路器已经打开    if (!this._circuitBreaker.AllowRequest)    {        return await Task.FromResult("Please wait for sometimes");    }    _logger.LogInformation($"RunFallback");    return await Task.FromResult<string>($"RunFallbackAsync---OrderId={_orderId}");}

}
Here are a few places to note:

Constructors must have ihystrixcommandoptions this parameter
Runasync is where the call is actually executed
Runfallbackasync is for some reason unable to get the return result when it will be executed where the so-called graceful downgrade.
The next thing to do is to register in startup.

public void Configureservices (iservicecollection services)
{
Services. Addsingleton ();
Services. Addhystrixcommand ("Order", Configuration);

services.AddMvc();

}
Can see, in the addition of the fuse command, also used the configuration of this parameter, which means that we have less configuration!!

Configuration is put into the appsettings.json inside, see below How to configure:

{
"Hystrix": {
"Command": {
"Default": {
"Circuitbreaker": {
is enabled, the default is True
"Enabled": True,
Minimum number of fuse triggers within a specified time window
"Requestvolumethreshold": 5,
How much time after the fuse to try to request
"Sleepwindowinmilliseconds": 5000,
What percentage of failure rate is reached after the fuse
"Errorthresholdpercentage": 50,
Whether to force the fuse to open
"ForceOpen": false,
Whether to force the fuse off
"Forceclosed": false
},
Whether to enable fallback
"Fallback": {
"Enabled": True
}
}
}
}
}
Need to add a node named Hystrix, inside the command node is the place we want to pay attention to!

Default, which is configured for all command! If you have a particular command to configure separately, you can add the appropriate command node under commands.

Other configuration items have been interpreted in a commented manner.

The following diagram simulates the availability of order services from available---unavailable.

In addition to the service is not available, there may be a situation where the probability will be relatively large, time-out!

For example, there is a service that is usually responsive, suddenly for some time without knowing what the reason, processing the request is a lot slower, this period of time the client has been waiting for a long time, even timed out.

When this happens, a time-out is usually set, as long as there is no response in this time is considered to be a timeout!

You can complete the timeout configuration by using the following configuration:

{
"Hystrix": {
"Command": {
"Default": {
"Execution": {
"Timeout": {
"Enabled": True
},
"Isolation": {
"Strategy": "THREAD",
"Thread": {
Timeout period
"Timeoutinmilliseconds": 1000
}
}
},
}
}
}
}
Summarize
Here are just a few of the more common and simple features, it can also combine multiple requests, caching requests and many other useful functions. Overall, the steeltoe of the fuse function, used up is relatively simple, but also more flexible.

Additional configuration and instructions can be found in the official documentation.

Sample code for this article:

Circuitbreakerdemo

If you think this article is good or something, you can click on the "Recommended" button in the lower right corner, because your support is my biggest motivation to continue writing and sharing!
Catcher (Huangwenqing)

Circuit breaker in. NET Core

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.