Using a circuit breaker in Spring boot

Source: Internet
Author: User
Tags switches

Circuit breaker itself is an overload protection device on the circuit, when the circuit has a short circuit, it can cut off the fault circuit in time to prevent serious consequences. Control the latency and failure of dependent services through service fusing (also known as break-through), downgrade, current-limit (isolation), asynchronous RPC, and so on, preventing the entire service avalanche. A circuit breaker can be decorated and detects a protected function call. Determines whether the call is executed or rolled back depending on the current state. Typically, a circuit breaker implements three types of states: Open, Half-open, and closed:

    1. Calls to the closed state are executed, transaction metrics are stored, and these metrics are necessary to implement a health policy.
    2. If the system health condition becomes worse, the circuit breaker is in open state. In this state, all calls are immediately rolled back and no new calls are generated. The purpose of the open state is to give the server the time to reply and handle the problem.
    3. Once the circuit breaker enters an open state, the time-out timer starts to tick. If the timer expires, the circuit breaker switches to the Half-open state. The Half-open state call is performed intermittently to determine whether the problem has been resolved. If resolved, the state switches back to the closed state.

The basic idea behind a circuit breaker is very simple. Wraps a protected function call in a circuit breaker object that monitors the failure. Once the fault reaches a certain threshold, the circuit breaker will trip, and any further calls to the circuit breaker will return an error, and no protected call will be made at all. Usually, if the circuit breaker trips, you also need some kind of monitor alarm.

How to use hystrix quickly? Follow me below 1234 ...

1. Add @enablecircuitbreaker Annotations

@EnableCircuitBreaker @springbootapplication@enableeurekaclient@enablefeignclients  Public class droolsappapplication {    publicstaticvoid  main (string[] args) {        Springapplication.run (droolsappapplication. class , args);}    }

Hystrix The overall execution process, first, the command calls the Run method, and if the Run method times out or throws an exception, and demotion processing is enabled, the Getfallback method is called for demotion;

2. Using @hystrixcommand annotations

@HystrixCommand (Fallbackmethod = "Reliable")     PublicString readinglist () { for(inti = 0; I < 10; i++) {            Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }        }        return"Jinpingmei"; }     PublicString Reliable () {return"Interesting book"; }

3. Adding references

    Compile ("Org.springframework.cloud:spring-cloud-starter-hystrix")    compile (' Org.springframework.cloud:spring-cloud-starter-turbine ')

4. Set timeout period

Hystrix.command. default. execution.isolation.thread.timeoutinmilliseconds=5000

The results of the implementation are as follows:

Normal should return:

You do not like Jinpingmei, want to like interesting books, so use comfortable ah, @EnableCircuitBreaker this note is so powerful?

Hystrixcommandaspect uses AOP to intercept all @hystrixcommand annotations, allowing @hystrixcommand to be integrated into spring boot,

The key code for Hystrixcommandaspect is as follows:

1. Method Hystrixcommandannotationpointcut () defines the Intercept annotation Hystrixcommand

2. Method Hystrixcollapserannotationpointcut () defines the Intercept annotation Hystrixcollapser

3. Method Methodsannotatedwithhystrixcommand (...) by @around (...) Methods to intercept all Hystrixcommand and hystrixcollapser annotations. See method notes in detail

@Aspect
public class Hystrixcommandaspect {

Private static final Map
static {
Meta_holder_factory_map = Immutablemap.. Put (Hystrixpointcuttype.command, New Commandmetaholderfactory ())
. Put (Hystrixpointcuttype.collapser, New Collapsermetaholderfactory ())
. build ();
}

@Pointcut ("@annotation (Com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand)")

public void Hystrixcommandannotationpointcut () {
}

@Pointcut ("@annotation (Com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser)")
public void Hystrixcollapserannotationpointcut () {
}

@Around ("Hystrixcommandannotationpointcut () | | | Hystrixcollapserannotationpointcut () ")
Public Object Methodsannotatedwithhystrixcommand (final Proceedingjoinpoint joinpoint) throws Throwable {
method = Getmethodfromtarget (Joinpoint);
Validate.notnull (method, "failed to get method from Joinpoint:%s", joinpoint);
if (Method.isannotationpresent (hystrixcommand.class) && method.isannotationpresent (hystrixcollapser.class )) {
throw new IllegalStateException ("method cannot is annotated with Hystrixcommand and Hystrixcollapser" +
"Annotations at the same time");
}
Metaholderfactory metaholderfactory = Meta_holder_factory_map.get (Hystrixpointcuttype.of (method));
Metaholder Metaholder = metaholderfactory.create (joinpoint);
Hystrixinvokable invokable = Hystrixcommandfactory.getinstance (). Create (Metaholder);
Executiontype Executiontype = Metaholder.iscollapserannotationpresent ()?
Metaholder.getcollapserexecutiontype (): Metaholder.getexecutiontype ();
Object result;
try {
result = Commandexecutor.execute (invokable, Executiontype, Metaholder);
} catch (Hystrixbadrequestexception e) {
Throw E.getcause ();
}
return result;
}

So how hystrixcommandaspect is initialized, is implemented by hystrixcircuitbreakerconfiguration

@Configuration  Public class hystrixcircuitbreakerconfiguration {@Bean public hystrixcommandaspect Hystrixcommandaspect () {returnnew  hystrixcommandaspect ();}

So who's going to trigger hystrixcircuitbreakerconfiguration execution initialization

First look at the spring.factories in the Spring-cloud-netflix-core**.jar package, this configuration is triggered by the annotation enablecircuitbreaker

Org.springframework.cloud.client.circuitbreaker.enablecircuitbreaker=  Org.springframework.cloud.netflix.hystrix.HystrixCircuitBreakerConfiguration


So @enablecircuitbreaker how to trigger Hystrixcircuitbreakerconfiguration
Through the source view, this class initializes the Enablecircuitbreakerimportselector class through @import

@Target (Elementtype.type) @Retention (retentionpolicy.runtime) @Documented @inherited@import ( Enablecircuitbreakerimportselector. class ) public @Interface  enablecircuitbreaker {}

Enablecircuitbreakerimportselector is the Springfactoryimportselector subclass. This class executes the selectimports (Annotationmetadata metadata) method after initialization. This method obtains its configuration from the Spring.factories file based on the annotations initiated by the annotation (referred to here as @enablecircuitbreaker) to initialize @ The configuration class (here is Org.springframework.cloud.netflix.hystrix.HystrixCircuitBreakerConfiguration), which eventually initializes the Hystrixcommandaspe CT class to intercept the Hystrixcommand function

The above is through @enablecircuitbreake can open hystrix principle. Hystrix used the Observer Mode Abstractcommand.executecommandandobserve () mode, next time let's go into the observer pattern. Welcome to shoot Bricks!

Using a circuit breaker in Spring boot

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.