SpringCloud (Finchley version) tutorial (Four): circuit breaker (Hystrix)

In the micro-service architecture, according to the service to be split into a number of service can call each other (RPC) services between a service and can be used RestTemplate + Ribbon Feign and call this Spring Cloud. In order to ensure availability, single service often cluster deployment. As the network reasons or for their own reasons, the service does not guarantee 100% available, if a single service issue arise, to call this service will be thread is blocked, at this time if the influx of a large number of requests, Servlet container thread resources will be consumed completed , resulting in paralysis of service. Dependencies between services and service failures will spread, will service the entire micro system have serious consequences disastrous, this is the "avalanche" effect service failure.

To solve this problem, the industry proposed circuit breaker model.

I. Introduction breaker

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

- Excerpt from the official website

Netflix Hystrix open source components, to achieve the cut-out mode, SpringCloud of the components were integrated. In the micro-service architecture, a request need to call multiple services are very common, as shown below:

HystrixGraph.png

The deeper service If a fault occurs, it will lead to cascading failures. When the call is not available for a particular service reaches a threshold (Hystric 5 seconds 20 times) circuit breaker will be opened.

HystrixFallback.png

After breaking open, can be used to avoid cascading failure, fallback method may return directly to a fixed value.

Second, prepare for work

This article is based on an article in the engineering, construction started on the first article, start the eureka-server project; project start service-hi, the port is 8762.

Third, the use of circuit breakers in the ribbon

改造serice-ribbon 工程的代码,首先在pox.xml文件中加入spring-cloud-starter-netflix-hystrix的起步依赖:

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在程序的启动类ServiceRibbonApplication 加@EnableHystrix注解开启Hystrix:
package com.liu.example.serviceribbon;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableHystrix
public class ServiceRibbonApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceRibbonApplication.class, args);
    }

    @Bean
    @LoadBalanced
    RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

改造HelloService类,在hiService方法上加上@HystrixCommand注解。该注解对该方法创建了熔断器的功能,并指定了fallbackMethod熔断方法,熔断方法直接返回了一个字符串,字符串为”hi,”+name+”,sorry,error!”,代码如下:

@Service
public class HelloService {

    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "hiError")
    public String hiService(String name) {
        return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class);
    }

    public String hiError(String name) {
        return "hi,"+name+",sorry,error!";
    }

}

启动:service-ribbon 工程,当我们访问http://localhost:8764/hi?name=forezp,浏览器显示:

hello! 我的端口号是:8762

此时关闭 service-hi 工程,当我们再访问http://localhost:8764/hi?name=forezp,浏览器会显示:

hi ,forezp,orry,error!

这就说明当 service-hi 工程不可用的时候,service-ribbon调用 service-hi的API接口时,会执行快速失败,直接返回一组字符串,而不是等待响应超时,这很好的控制了容器的线程阻塞。

四、Feign中使用断路器

Feign是自带断路器的,在D版本的Spring Cloud之后,它没有默认打开。需要在配置文件中配置打开它,在配置文件加以下代码:

feign:
hystrix:
enabled: true

server:
  port: 8765
spring:
  application:
    name: service-feign
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

feign:
  hystrix:
    enabled: true

基于service-feign工程进行改造,只需要在FeignClient的SchedualServiceHi接口的注解中加上fallback的指定类就行了:

@FeignClient(value = "service-hi",fallback = SchedualServiceHiHystric.class)
public interface SchedualServiceHi {
    @RequestMapping(value = "/hi",method = RequestMethod.GET)
    String sayHiFromClientOne(@RequestParam(value = "name") String name);
}

SchedualServiceHiHystric需要实现SchedualServiceHi 接口,并注入到Ioc容器中,代码如下:

package com.liu.example.sericefeign.service;

import org.springframework.stereotype.Component;

@Component
public class SchedualServiceHiHystric implements SchedualServiceHi{

    @Override
    public String sayHiFromClientOne(String name) {
        return "sorry "+name;
    }
}

Start four servcie-feign project browser to open http: // localhost:? 8765 / hi name = forezp, note that at this time the project does not start service-hi, web page display:

sorry forezp

Open service-hi engineering, accessed again, the browser displays:

! Hello my port number is: 8762

This proves that the circuit breaker played a role.

Download this article Source:  https://github.com/MrLiu1227/MySpringCloud.git

Guess you like

Origin www.cnblogs.com/liuyuan1227/p/11220283.html