Fusing the drop
Concept — why — — — — — — — — — how to use – running principle — — — — — — — — — — — fusing of relegation – timeout – try again — — — — — — package — — — — — consul and polly integrated into the project
First of all, let’s make it clear that the basic unit of microservice architecture is microservice, which means the main body is microservice —- and each microservice has its own structure. When these structures are combined into a single microservice (which belongs to the folder hierarchy), the same structure will appear for each microservice. At this time, many students will ask why the same files between various micro services can not be used, but there will be so much redundancy. The reasons for doing this are: 1) to ensure the independence of micro-services; 2) to ensure the stability of micro-services. Let me give you an example: microservices are like each of us, each of us makes up a social structure, and microservices are similar to this scenario. As you all know, everyone has the same structure. If everybody structures all together. You can imagine what could go wrong. It’s all messed up. The same goes for microservices. The first priority of any microservice is to ensure independence. So I’m using folder hierarchy for microservices.
For when to layer with assemblies. Just to be clear, each microservice has its own domain model (the problem and problem boundary we talked about yesterday). If multiple microservices are between. There are times when resources have to be shared, shared resources are immutable, and changes do not affect the logic of each microservice. Then we extract this general logic and use DLLS to reference it in layers, such as: communication between micro services, authentication, traffic limiting, load balancing and so on. So let’s call this layer the tool layer.
What is a circuit breaker
Circuit breaker is a kind of strategic coping mechanism when the called end breaks down and times out.
A fuse is like a fuse. Let’s take a look at a fuse
Why use circuit breakers
1. Abnormal service invocation (including timeout and outage)
If the service fails several times in a row, the service is fussed for a period of time,
What is a downgrade
Why downgrade
1. Active service degradation (selective abandonment)
Actively perform an exception return on the service
2. Abnormal service degradation
If the service invocation times out or goes down, it returns according to a custom policy.
The purpose of the fuse downgrade in the project is to ensure the flexibility of the system and make the system highly available
How to use circuit breaker downgrade in the project
Fuse downgrade tool
1, Polly
2, Hystrix
How to use Polly in microservices
The main function
Retry
Circuit breaker
Timeout detection
Cache
FallBack
Polly官网 address
www.thepollyproject.org/
Polly is installed
Nuget Microsoft.Extensions.Http.Polly
How to use Polly
conditions
1. Micro-service projects
2, Polly
Polly HTTP extension
steps
1. Install through Nuget first
Microsoft.Extensions.Http.Polly
Add AddPolicyHandler() to HttpClient.
3. Then test outages and timeouts in team services
3. Select the circuit breaker strategy first
.AddPolicyHandler(Policy<HttpResponseMessage>.Handle<Exception>().CircuitBreakerAsync(3, TimeSpan.FromSeconds(10), (ex, Ts) => {console. WriteLine($" service {name} circuit breaker open, Exception Message: {ex.exception.message}"); Console.WriteLine($" service {name} breaker start time: {ts.totalseconds}s"); }, () => {console. WriteLine($" service {name} circuit breaker reset "); = > {}, () Console. WriteLine (${name} "service circuit breaker (turn for a moment, a moment of) the half open"); }))Copy the code
5. Then choose a downgrading strategy
Var fallbackResponse = new HttpResponseMessage {Content = new StringContent(" Please try again later "), StatusCode = HttpStatusCode. GatewayTimeout}; .AddPolicyHandler(Policy<HttpResponseMessage>.HandleInner<Exception>().FallbackAsync(options.httpResponseMessage, Async b = > {/ / 1, relegation printing anomaly Console. WriteLine ($" {name} started downgrading of services, the exception Message: {b.E xception. Message} "); / / 2, after degradation data to the Console. WriteLine ($" service {name} relegation Content response: {options. HttpResponseMessage. Content. the ToString ()} "); await Task.CompletedTask; }))Copy the code
6. Then select a retry policy
.AddPolicyHandler(Policy<HttpResponseMessage>
.Handle<Exception>()
.RetryAsync(options.RetryCount)
)
Copy the code
7. Finally, choose the timeout mechanism
.AddPolicyHandler(Policy.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromSeconds(options.TimeoutTime)));
Copy the code
How is Polly encapsulated in a project
conditions
1, IServiceCollection extension class
2. HttpClientPolly option class
steps
1, create PollyHttpClientServiceCollectionExtensions class
// <param name="services"> IOC container </param> // <param > // <param Name ="name">HttpClient name </param> // <param name="action"> Fuse degrade configuration </param> // <param name="TResult"> </param> // </returns> public static IServiceCollection AddHttpClientPolly(this IServiceCollection services,string Name,Action<HttpClientPollyOptions> Action) {// create an option configuration class HttpClientPollyOptions options = new HttpClientPollyOptions(); action(options); Services. AddHttpClient(name) //1.1 Downgrade policy .AddPolicyHandler(Policy<HttpResponseMessage>.HandleInner<Exception>().FallbackAsync(options.httpResponseMessage, Async b = > {/ / 1, relegation printing anomaly Console. WriteLine ($" {name} started downgrading of services, the exception Message: {b.E xception. Message} "); / / 2, after degradation data to the Console. WriteLine ($" service {name} relegation Content response: {options. HttpResponseMessage. Content. the ToString ()} "); await Task.CompletedTask; }) // 1.2 Circuit breaker policy .AddPolicyHandler(Policy<HttpResponseMessage>.Handle<Exception>().CircuitBreakerAsync(options.CircuitBreakerOpenFallCoun T, TimeSpan. FromSeconds (options. CircuitBreakerDownTime), (ex, ts) = > {Console. WriteLine ($" service {name} circuit breaker opens, the exception message: {ex.Exception.Message}"); Console.WriteLine($" service {name} breaker start time: {ts.totalseconds}s"); }, () => {console. WriteLine($" service {name} circuit breaker closed "); = > {}, () Console. WriteLine (${name} "service circuit breaker (time control, automatic switch) half open"); })) // 1.3 Retry Policy.addPolicyHandler (Policy<HttpResponseMessage>.handle <Exception>().retryAsync (options.retrycount)) // AddPolicyHandler(policy.timeoutAsync <HttpResponseMessage>(timespan.fromseconds (options.timeouttime))); return services; }Copy the code
2, then create a fuse, degrade, retry, timeout configuration class HttpClientPollyOptions
// </summary> public int TimeoutTime {set; get; } /// </summary> // </summary> public int RetryCount {set; get; } / / / < summary > / / / how often perform anomaly, open short circuiter (example: 2 times failure, open circuit breaker) / / / < summary > public int CircuitBreakerOpenFallCount {set; get; } /// <summary> /// Circuit breaker startup time (for example, 2 seconds, the circuit breaker automatically starts and closes after 2 seconds) /// </summary> public int CircuitBreakerDownTime {set; get; } /// <summary> /// degraded processing (encapsulate abnormal messages into normal messages and return them, and then respond to them, for example: the system is busy, please deal with later.....) /// </summary> public HttpResponseMessage httpResponseMessage { set; get; }Copy the code
3. Wrapped code invocation
services.AddPollyHttpClient("tony",options => {
options.TimeoutTime = 1;
options.RetryCount = 3;
options.CircuitBreakerOpenFallCount = 2;
options.CircuitBreakerDownTime = 100;
options.httpResponseMessage = fallbackResponse;
});
Copy the code