Spring Cloud Circuit Breaker Hystrix

Source: Internet
Author: User

In the micro-service architecture, there are so many service units, if one unit fails, it will cause the fault spread due to the dependency relationship, eventually lead to the whole system paralysis, the architecture is more unstable than the traditional architecture. In order to solve this problem, the circuit breaker mode is produced.

What is a circuit breaker?

The circuit breaker model originates from Martin Fowler's circuit breaker. "Circuit Breaker" itself is a switch device, used in the circuit to protect the line overload, when the circuit has a short circuit, "circuit breaker" can timely cut off the fault circuit, to prevent the occurrence of overload, heat, and even fire serious consequences.

In a distributed architecture, the role of the circuit breaker pattern is similar, when a service unit fails (similar to a short-circuit with electrical appliances), through the fault monitoring of the circuit breaker (similar to a fuse fuse), to the caller returned an error response, rather than a long wait. This does not cause the thread to fail to be released for a long time because of the invocation of the fault service, thus avoiding the spread of the fault in the distributed system.

Netflix Hystrix

The hystrix is used in spring cloud to realize the function of the circuit breaker. Hystrix is one of Netflix's open source MicroServices framework packages designed to provide greater fault tolerance for latency and failures by controlling the nodes that access remote systems, services, and third-party libraries. The Hystrix features thread and signal isolation with fallback mechanism and breaker functionality, request caching and request packaging, and monitoring and configuration.

Let's take a simple example to introduce the use of spring cloud Hystrix

First add the spring cloud Hystrix dependencies to the project:

<dependency>    <groupId>org.springframework.cloud</groupId>    <artifactId> Spring-cloud-starter-hystrix</artifactid></dependency>

Adding the @enablecircuitbreaker open fuse function to the startup class of the project

@SpringBootApplication @enablediscoveryclient@enablecircuitbreaker  Public class Application {    @Bean    @LoadBalanced    public  resttemplate resttemplate () {         return New resttemplate ();    }      Public Static void Main (string[] args) {        springapplication.run (application. class , args);}    }

You can also use the springcloud corresponding @springcloudapplication annotation to decorate the startup class, as you can see from the code, which contains the other three annotations, as well as a standard Springcloud program that contains service discovery and fusing mechanisms.

@Target ({elementtype.type}) @Retention (retentionpolicy.runtime) @ Documented@inherited@springbootapplication@enablediscoveryclient@enablecircuitbreaker public @ Interface Springcloudapplication {}

New ComputeService class to specify callback methods by adding annotations on functions that use the Ribbon consumer service @HystrixCommand

@Service Public classComputeservice {@AutowiredPrivateresttemplate resttemplate; @HystrixCommand (Fallbackmethod="Addservicefallback")     PublicString AddService () {returnResttemplate.getforentity ("http://COMPUTE-SERVICE/add?a=10&b=20", String.class). GetBody (); }     PublicString Addservicefallback () {return "Error"; }}

The controller that provides the rest interface changes to call Computeservice's AddService

@RestController  Public class Consumercontroller {    @Autowired    private  computeservice computeservice;     " /add ", method = requestmethod.get)    public  String Add () {          return  computeservice.addservice ();    }}

Verify the callback for the circuit breaker

    • Start Eureka-server, Compute-service, Eureka-ribbon project in turn
    • Access http://localhost:1111/to see the status of the registry
    • Visit Http://localhost:3333/add, page display: 30
    • After you close the Compute-service service and then visit Http://localhost:3333/add, the page displays: Error
Feign using Hystrix

Note that this is said to be "use", there is no mistake, we do not need to introduce hystix,feign in the Feigh project has relied on hystrix, we can do before any modification, try the following your operation:

    • Start Eureka-server, Compute-service, Eureka-feign project in turn
    • Access http://localhost:1111/to see the status of the registry
    • Access Http://localhost:3333/add, call Eureka-feign's service, the service will go to invoke Compute-service service, calculate the value of 10+20, page display 30
    • Close the Compute-service service, Access Http://localhost:3333/add, we get the following error message
 whitelabel Error pagethis application has no   Explicit  mapping for /error, so is seeing this  as   a fallback. Sat June  25  22 : 10 : 05  CST 2016  there is an unexpected error (type  =internal Server error, Status= ). Add timed -out  and no fallback Available. 

If you are careful enough, you will find that the error in the Ribbon is different, see add timed-out and no fallback available this sentence, perhaps you have guessed what, see our console, you can see the error message from hystrix-core-1.5.2.jar , so in this project, we have to learn how to use feign integrated hystrix.

Use @FeignClient the Fallback property in annotations to specify the callback class

 @FeignClient (value =  " compute-service   ", fallback = Computeclienthystrix. class  )  public   Interface   Computeclient {@RequestMapping (method  = Requestmethod.get, Value =  " /add   " ) Integer Add (@RequestParam (value  =  a   ") Integer A, @RequestParam (value = "  b   " ) Integer b);} 

Create the callback class ComputeClientHystrix , implemented @FeignClient by the interface, at this time the implementation of the method is the corresponding @FeignClient interface map of the fallback function.

@Component  Public class Computeclienthystrix implements Computeclient {    @Override    public"A  ""b") Integer b) {        return -9999 ;    }}

Then verify with the previous method that the page returns 9999 if the Compute-service service is unavailable.

  

Spring Cloud Circuit Breaker Hystrix

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.