(C) Spring Cloud tutorial --Hystrix (F version)

Reference: Fang Zhipeng column

Introduction 1. 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.

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.

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.

2. Use a circuit breaker in the Ribbon

Code service-ribbon renovation project, first started adding dependent spring-cloud-starter-netflix-hystrix in pox.xml file:

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

在程序的启动类ServiceRibbonApplication 加@EnableHystrix注解开启Hystrix:

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!”,代码如下:

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@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=zang,浏览器显示:

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

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

3. Feign中使用断路器

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

feign.hystrix.enabled: true

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

import com.zang.servicefeign.clients.fallback.SchedualServiceHiHystric;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@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 need to implement the interface, and Ioc is injected into the container, as follows:

import com.zang.servicefeign.clients.SchedualServiceHi;
import org.springframework.stereotype.Component;

@Component
public class SchedualServiceHiHystric implements SchedualServiceHi {
    @Override
    public String sayHiFromClientOne(String name) {
        return "sorry, you are fail,"+name;
    }
}

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

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

 This proves that the circuit breaker played a role.

 

Guess you like

Origin www.cnblogs.com/zjfjava/p/12189517.html