Take doctrine Springcloud | Fourth article: Circuit breaker (Hystrix)

Source: Internet
Author: User

In a microservices architecture, the service is split into services according to the business, and the service and service can call each other (RPC), which can be invoked with Resttemplate+ribbon and feign in spring cloud. To ensure their high availability, a single service is typically deployed in a cluster. Due to network reasons or their own reasons, the service does not guarantee that 100% is available, if a single service problem, call the service will be a thread blocking, if there is a large number of requests, the servlet container thread resources will be exhausted, resulting in service paralysis. The dependence between service and service, the failure will spread, will have disastrous serious consequence to the whole micro-service system, this is the "avalanche" effect of service failure.

In order to solve this problem, the industry put forward the circuit breaker model.

First, Circuit breaker introduction

Netflix has created a library called Hystrix that implements the circuit breaker pattern. In a microservice architecture it was common to the multiple layers of service calls.

. --Excerpt from official website

Netflix opens up the Hystrix component, implements the circuit breaker mode, and springcloud the component. In a microservices architecture, it is very common for a request to invoke multiple services, such as:

Lower-level services can cause cascading failures if they fail. When a call to a particular service is not available to reach a threshold (Hystric is 5 seconds 20 times) The circuit breaker will be opened.

The fallback method can return a fixed value directly after the open circuit is opened to avoid cascading failures.

Ii. preparatory work

This article is based on the project of the previous article, first started the project of the previous article, started the Eureka-server project, the port is 1111; start the Service-hi project, its port is 2222.

Iii. use of circuit breakers in the Ribbon

Transform the code of the Serice-ribbon project, first in the Pox.xml file to add the Spring-cloud-starter-hystrix start-up dependency:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

In the program's startup class Serviceribbonapplication add @enablehystrix annotations to open Hystrix:

 PackageCom.example.springcloud.ribbon;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;Importorg.springframework.cloud.client.discovery.EnableDiscoveryClient;Importorg.springframework.cloud.client.loadbalancer.LoadBalanced;ImportOrg.springframework.cloud.netflix.hystrix.EnableHystrix;Import ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.web.client.RestTemplate, @EnableDiscoveryClient @springbootapplication@enablehystrix  Public classribbonapplication { Public Static voidMain (string[] args) {Springapplication.run (ribbonapplication.class, args); } @Bean @LoadBalanced resttemplate resttemplate () {return Newresttemplate (); }}

Transform the HelloService class and add @HystrixCommand annotations to the Hiservice method. The note creates a fuse function for the method and specifies the fallbackmethod fuse method, which directly returns a string with the string "Hi," "+name+", sorry,error! ", and the code is as follows

 PackageCom.example.springcloud.ribbon.service; ImportCom.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; Importorg.springframework.beans.factory.annotation.Autowired; ImportOrg.springframework.stereotype.Service; Importorg.springframework.web.client.RestTemplate; @Service Public classHelloService {@Autowired resttemplate resttemplate; @HystrixCommand (Fallbackmethod= "Hierror")     Publicstring Hiservice (string name) {returnResttemplate.getforobject ("http://service-hi/hi?name=" + Name, String.class); }     Publicstring Hierror (string name) {return"Hi," +name+ ", sorry,error!"; }}

Start: Service-ribbon project, when we visit Http://localhost:4444/hi?name=forezp, the browser displays:

Hi forezp,i am from port:2222

At this point the Service-hi project is closed, and when we revisit Http://localhost:4444/hi?name=forezp, the browser will show:

Hi, forezp,orry,error!

This means that when the Service-hi project is unavailable, Service-ribbon calls the API interface of Service-hi, performs a quick failure, returns a set of strings directly, rather than waiting for a response timeout, which controls the container's thread blocking well.

Iv. use of circuit breakers in feign

The feign is self-contained, and in the D version of Spring Cloud, it is not turned on by default. It needs to be configured in the configuration file to open it, under the code in the configuration file:

Feign.hystrix.enabled=True

Based on the Service-feign project, simply add the fallback specified class to the annotations of the Feignclient Schedualservicehi interface:

@FeignClient (value = "Service-hi", fallback = schedualservicehihystric.  Class)publicinterface  Schedualservicehi {    = "/hi", method =  Requestmethod.get)    = "name") String name);

The schedualservicehihystric needs to implement the Schedualservicehi interface and inject it into the IOC container with the following code:

@Component  Public class Implements Schedualservicehi {    @Override    public  string Sayhifromclientone (string name) {         return "Sorry" +name;}    }

Start four Servcie-feign project, browser Open HTTP://LOCALHOST:5555/HI?NAME=FOREZP, note at this time Service-hi project does not start, Web page display:

Sorry Forezp

Open Service-hi Project, visit again, browser display:

Hi forezp,i am from port:2222

This proves that the circuit breaker is playing a role.

Five, Hystrix Dashboard (Circuit breaker: hystrix instrument panel)

Based on the Service-ribbon transformation, the feign transformation is the same as this.

The first choice to introduce Spring-cloud-starter-netflix-hystrix-dashboard in Pom.xml is the initial dependency:

<!--  Dashboards--        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-actuator</artifactId>        </dependency>        <dependency >            <groupId>org.springframework.cloud</groupId>            <artifactId> Spring-cloud-starter-netflix-hystrix-dashboard</artifactid>        </dependency>

To add @enablehystrixdashboard annotations to the main program startup class, turn on Hystrixdashboard:

@SpringBootApplication @enablediscoveryclient@enablehystrix@enablehystrixdashboard  Public class serviceribbonapplication {    publicstaticvoid  main (string[] args) {        Springapplication.run (serviceribbonapplication. class , args);    }    @Bean    @LoadBalanced    resttemplate resttemplate () {        returnnew  Resttemplate ();    }}

Open Browser: Access Http://localhost:4444/hystrix, the interface is as follows:

Click on Monitor stream to go to the next interface, visit: HTTP://LOCALHOST:4444/HI?NAME=FOREZP

The monitoring interface will appear:

Take doctrine Springcloud | Fourth article: 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.