Spring Cloud Starter Series IV: Using Hystrix to implement fault-tolerant protection for circuit breakers

Source: Internet
Author: User

In MicroServices, we split the system into a number of service units that are interdependent between units through service registration and subscription consumption. But what if there are some services that have problems?

For example, there are three services (ABC), and a calls B,b C. The request for B calls C is suspended and waits because of a network delay or a problem with the C itself code that causes B to be slow to respond.

In the case of high concurrent access, these suspended threads are not released, blocking subsequent requests and eventually causing B to hang up. And so on, a may also hang, causing the whole system to crash.

To solve the whole problem, Spring Cloud uses Hystrix for service fault tolerance protection, including circuit breakers, thread isolation and a series of protection functions, today we look at how to implement the circuit breaker through Hystrix.

One, what is Spring Cloud hystrix? What is a circuit breaker?

The Spring Cloud Hystrix is based on Netflix's open source framework Hystrix, which is designed to provide strong fault tolerance for latency and failures by controlling the nodes that access remote systems, services, and third parties.

Circuit breaker similar to the inside of our home in the strong electrical box used in the leakage circuit breaker, when the service unit failure (similar to electrical short circuit), through the fault monitoring function of the circuit breaker (similar to a fuse), to the caller return an error response, avoid long waits, so as to avoid the failure to spread to the entire system.

Second, no circuit breaker in the case, the page display

Remember the Spring Cloud Starter Series we wrote earlier: three services (Eureka/hello-service/hello-consumer) using Eureka for service governance? We are experimenting on this.

    1. Start Eureka Service Registry, port number 1111
    2. Start Hello-service service provider, here we start two services, port number is 9090,9091
    3. Start the Hello-consumer service consumer, the port number is 9999; this time we visit Http://localhost:9999/hello-consumer many times is no problem
    4. The Hello-service port number of 9091 service is turned off, and then to visit Http://localhost:9999/hello-consumer, error

      PS: Here is why we have to visit multiple times because we are load balanced through the ribbon, and when we visit Http://localhost:9999/hello-consumer, we poll the two services that access Hello-service. When access to the port number is 9091 of the service to error, access to 9090 of the service will not be a problem.

Third, circuit breaker code implementation

Next we look at how the code implementation, we do not modify the service registry and service providers, only need to modify the service consumer Hello-consumer.

  1. Modify the Pom file to introduce hystrix dependencies
    <Projectxmlns= "http://maven.apache.org/POM/4.0.0"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelversion>4.0.0</modelversion>    <groupId>Com.sam</groupId>    <Artifactid>Hello-consumer</Artifactid>    <version>0.0.1-snapshot</version>    <Parent>        <groupId>Org.springframework.boot</groupId>        <Artifactid>Spring-boot-starter-parent</Artifactid>        <version>1.5.1.RELEASE</version>    </Parent>    <Properties>        <javaversion>1.8</javaversion>    </Properties>    <dependencymanagement>        <Dependencies>            <Dependency>                <groupId>Org.springframework.cloud</groupId>                <Artifactid>Spring-cloud-dependencies</Artifactid>                <version>Camden.sr6</version>                <type>Pom</type>                <Scope>Import</Scope>            </Dependency>        </Dependencies>    </dependencymanagement>    <Dependencies>        <!--introducing Eureka Client Dependencies -        <Dependency>            <groupId>Org.springframework.cloud</groupId>            <Artifactid>Spring-cloud-starter-eureka</Artifactid>        </Dependency>        <!--introducing ribbon dependencies, which are used to achieve load balancing, we're just using this first without making other introductions -        <Dependency>            <groupId>Org.springframework.cloud</groupId>            <Artifactid>Spring-cloud-starter-ribbon</Artifactid>        </Dependency>        <!--introducing Hystrix dependencies to implement service-tolerant protection -         <dependency><groupId> Org.springframework.cloud</groupId><Artifactid  >spring-cloud-starter-hystrix</artifactid></ Dependency >     </Dependencies></Project>
  2. Modify the Startup class, append annotations @enablecircuitbreaker, turn on the circuit breaker
    @EnableDiscoveryClient @springbootapplication@EnableCircuitBreaker  Public classConsumerapp {//@Bean applied on a method to set the method return value to a Bean@Bean @LoadBalanced//@LoadBalanced for load Balancing     Publicresttemplate resttemplate () {return Newresttemplate (); }         Public Static voidMain (string[] args) {Springapplication.run (Consumerapp.class, args); }}

    This time you will find that this startup class added three annotations, this is not very troublesome? Okay, we can use annotations @springcloudapplication

    @SpringCloudApplication Public classConsumerapp {//@Bean applied on a method to set the method return value to a Bean@Bean @LoadBalanced//@LoadBalanced for load Balancing     Publicresttemplate resttemplate () {return Newresttemplate (); }         Public Static voidMain (string[] args) {Springapplication.run (Consumerapp.class, args); }}

    @SpringCloudApplication = @EnableDiscoveryClient [email protected]+ @EnableCircuitBreaker, from the source can be seen:

    @Target (Elementtype.type) @Retention (retentionpolicy.runtime) @Documented @inherited@ Springbootapplication@enablediscoveryclient@enablecircuitbreaker public @Interface  springcloudapplication {}
  3. Append Service
    @Service Public classConsumerservice {@Autowired resttemplate resttemplate; @HystrixCommand (Fallbackmethod= "ErrorMsg")     PublicString Consumer () {//Call the Hello-service service, and note that the service name is used instead of the specific Ip+portResttemplate.getforobject ("Http://hello-service/hello", String.class); return"Hello Consumer finish!!!"; }     PublicString errormsg () {return"Error!!!"; }}

    We put the implementation of the call Resttemplate in the original controller into the service, and specify the callback method by @hystrixcommand, and call the method when an error occurs.

  4. Modify Controller
    /*** Instead of calling Resttemplate directly, * it is implemented by invoking a service **/@RestController Public classConsumercontroller {@Autowired//resttemplate resttemplate;Consumerservice Service; @RequestMapping ("/hello-consumer")     PublicString Helloconsumer () {//        //Call the Hello-service service, and note that the service name is used instead of the specific Ip+port//Resttemplate.getforobject ("Http://hello-service/hello", string.class);returnService.consumer (); }}
  5. Test, multiple access, when the error, will show the following content

Done!

Spring Cloud Starter Series IV: Using Hystrix to implement fault-tolerant protection for circuit breakers

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.