7. A preliminary study on Hystrix of Spring-Cloud service fault-tolerant protection

      In the microservice architecture, there are multiple service units. If one unit fails, it is easy to spread the failure due to dependencies, and eventually lead to the paralysis of the entire system. This architecture is more unstable than the traditional architecture. In order to solve this problem, a series of service protection mechanisms such as circuit breakers have been developed.

    The "circuit breaker" itself is a switching device used to protect the circuit from overload. When there is a short circuit in the circuit, the "circuit breaker" can cut off the faulty circuit in time to prevent serious consequences such as overload, heat generation and even fire.

      In the distributed architecture, the role of the circuit breaker mode is similar. When a service unit fails (similar to a short circuit in an electrical appliance), the circuit breaker fault monitoring (l similar to a fuse fuse) returns a Error responses instead of long waits. In this way, the thread will not be occupied for a long time and not released due to calling the faulty service, and the spread of the fault in the distributed system will be avoided.

      In response to the above problems, Spring Cloud Hystrix implements a series of service protection functions such as circuit breakers and thread isolation. It is also based on Hystrix, Netflix's open source framework, which aims to provide robust fault tolerance to latency and failures by controlling those nodes accessing remote systems, services, and third-party libraries. Hystrix has powerful functions such as service degradation, service fuse, thread and signal isolation, request cache merging, and service monitoring. -----From "Spring Cloud Microservices in Practice"


                                                 The above picture shows a normal microservice call


Hystrix fallback prevents cascading failures       when a service fails, and service failures in lower-level services can lead to cascading failures for users. When the detection of a particular service reaches a certain threshold (the default in Hystrix is ​​20 failures in 5 seconds), the circuit opens and does not respond. In the case of errors and open circuits, developers can provide fallbacks (i.e. service degradation).

Demo without fuses

Start a highly available registry

Start the service provider (port=8081,port=8082)

Start the consumer (access via Robbin load balancing)

The previous blog has demonstrated that when both service providers are in normal use, if the service provider on port 8082 is disabled, the following error will be reported when the consumer load balancer accesses port 8082 in rotation:

add fuse

1. Introduce dependency hystrix dependency in pom.xml

<project xmlns="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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>6.spring-cloud-hystrix-consumer</groupId>
<artifactId>hystrix-consumer</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>spring-cloud Maven Webapp</name>
<url>http://maven.apache.org</url>
<!--springboot采用1.5.x 对应springcloud版本为 Dalston -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath />

</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Dalston.RELEASE</spring-cloud.version>
</properties>
<dependencies>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>


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


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


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId >org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--Introduce ribbon load balancing-->
<dependency>
<groupId>org.springframework.cloud </groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
<!-- I have been stepping on the pit for a long time, that is, when copying the above code, I copied the scope test, which means that it is similar to closely participating in junit The test work, so it has been reported that the service cannot be found or the connection is refused -->
<!-- <scope>test</scope> -->
</dependency> <!--Introduce hystrix circuit breaker--> <dependency>


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

</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!-- 这样变成可执行的jar -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

2. Add an annotation

package com.niugang;


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.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.client.RestTemplate;


/**
 * 负责服务的发现与消费
 * 
 * @author niugang
 *
 */
@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix//这个注解就@EnableCircuitBreaker的代替
/*
 * @SpringCloudApplication
 * 包含了
 * @SpringBootApplication
 * @EnableDiscoveryClient
 * @EnableCircuitBreaker
 * 着三个注解
 */

@ComponentScan

public class Application {

   //负载均衡
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

3.controller

package com.niugang.controller;
import org.slf4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.niugang.service.HelloService;
@RestController
public class HelloController {

private final Logger logger = org.slf4j.LoggerFactory.getLogger(HelloController.class);

        @Resource

private HelloService helloService;
@RequestMapping(value = "/ribbon-consumer", method = RequestMethod.GET)
public String ribbon() {
return helloService.helloService();
}
}

4.service

package com.niugang.service;


import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
@Service
public class HelloService {
private final Logger logger = org.slf4j.LoggerFactory.getLogger(HelloService.class);
@Autowired
    private RestTemplate restTemplate;
    /**
     * @HystrixCommand:指定一些方法,这些方法应该是作为hystrix命令的进程
     * fallbackMethod:指定回退方法,降级处理,此方法应该和@HystrixCommand在一个类中,用来实现服务降级处理逻辑
     * 

     */

      @HystrixCommand(fallbackMethod="helloBackMethodFirst")
public String  helloService() {
logger.info("start invoke service");
//URI需要使用虚拟主机名(即服务名称,而不是主机名)
return restTemplate.getForEntity("http://service-provide/hello", String.class).getBody();
}
/**
* 通用降级函数
* @return
*/
@HystrixCommand(fallbackMethod="helloBackMethodSecond")
public  String  helloBackMethodFirst(){
//此处可能是另外一个网络请求,所以也可能出现错误
return  "error1";
}
/**
* 二次降级
* @return
*/
@HystrixCommand(fallbackMethod="helloBackMethodSecond")
public  String  helloBackMethodSecond(){
return  "error2";
}
}

启动消费者,正常访问返回如下


停用一个服务提供者,当负载均衡讯轮到停用的服务提供者时,返回如下:


这样的话熔断器起作用了,进行了服务的降级。

健康指标
连接断路器的状态也暴露在呼叫应用程序的/health端点中。


{
    "hystrix": {
        "openCircuitBreakers": [
            "StoreIntegration::getStoresByLocationLink"
        ],
        "status": "CIRCUIT_OPEN"
    },
    "status": "UP"
}
Hystrix指标流
要使Hystrix指标流包含对spring-boot-starter-actuator的依赖。这将使/hystrix.stream作为管理端点。
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324809321&siteId=291194637