spring boot 2.0.3+spring cloud (Finchley)4、熔断器Hystrix

在分布式系统中服务与服务之间的依赖错综复杂,一种不可避免的情况就是某些服务会出现故障,导致依赖于他们的其他服务出现远程调度的线程阻塞。某个服务的单个点的请求故障会导致用户的请求处于阻塞状态,最终的结果是整个服务的线程资源消耗殆尽。由于服务的依赖性,会导致依赖于该故障服务的其他服务也处于线程阻塞状态,最终导致这些服务的线程资源消耗殆尽,知道不可用,从而导致整个服务系统不可用,即雪崩效应。为了防止雪崩效应,产生了熔断器模型。

Hystrix是Netflix公司开源的一个项目,提供了熔断器功能,能阻止分布式系统中出现联动故障。Hystrix是通过隔离服务的访问点阻止联动故障的,并提供了故障解决方案,从而提高了整个分布式系统的弹性。

当服务的某个API接口的失败次数在一定时间内小于设定的阈值时,熔断器处于关闭状态,该API接口正常提供服务。当该API接口处理请求的失败次数大于设定的阈值时,hystrix判定该API接口出现了故障,打开熔断器,这时请求该API接口会执行快速失败的逻辑(即fallback回退的逻辑),不执行业务逻辑,请求的线程不会处于阻塞状态。处于打开状态的熔断器,一段时间后会处于半打开状态,并将一定数量的请求执行正常逻辑,剩余的请求会执行快速失败,若执行正常逻辑的请求失败了,则熔断器继续打开,若成功了,则关闭熔断器。这样熔断器就具有了自我修复的能力。

在RestTemplate和Ribbon上使用熔断器

需要已经成功配置Ribbon,可参考:spring boot 2.0.3+spring cloud (Finchley)2、搭建负载均衡Ribbon (Eureka+Ribbon+RestTemplate)

在eureka-ribbon-client工程中,使用了RestTemplate调用了eureka-client的“/hi”API接口,并使用ribbon做了负载均衡,在此基础上加入Hystrix熔断器功能。在pom文件中加入Hystrix起步依赖spring-cloud-starter-netflix-hystrix

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cralor</groupId>
    <artifactId>eureka-ribbon-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>eureka-ribbon-client</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>com.cralor</groupId>
        <artifactId>chap8-hystrix</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

在项目启动类加上@EnableHystrix注解,开启hystrix熔断器功能

@EnableHystrix
@SpringBootApplication
public class EurekaRibbonClientApplication {

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

修改RibbonService代码,在hi()方法上加上@HystrixCommand注解。有了该注解hi()方法就启用了Hystrix熔断器的功能,其中,fallbackMethod为处理回退(fallback)逻辑的方法。在本例子,直接返回了一个字符串。在熔断器打开的状态下,会执行fallback逻辑。fallback的逻辑最好是返回一些静态的字符串,不需要处理复杂的逻辑,也不会远程调用其他服务,这样方便执行快速失败,释放线程资源。如果一定要在fallback逻辑中远程调用其他服务,最好在远程调用其他服务时,也加上熔断器。

@Service
public class RibbonService {
    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "hiError")
    public String hi(String name){
        return restTemplate.getForObject("http://eureka-client/hi?name="+name,String.class);
    }
    public String hiError(String name){
        return "hi,"+name+",sorry,error!";
    }
}

RibbonConfig类

@Configuration
public class RibbonConfig {
    @Bean
    @LoadBalanced
    RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

RibbonController类

@RestController
public class RibbonController {
    @Autowired
    private RibbonService ribbonService;

    @GetMapping("/hi")
    public String hi(@RequestParam(required = false,defaultValue = "cralor") String name){
        return ribbonService.hi(name);
    }
}

依次启动eureka-server、eureka-client和eureka-ribbon-client。在浏览器访问http://localhost:8764/hi,会显示

关闭eureka-client,使其处于不可以状态,此时eureka-ribbon-client无法调用eureka-client的“/hi”接口,访问http://localhost:8764/hi

 由此可见,当eureka-client不可用时,调用eureka-ribbon-client的”/hi“接口会进入RibbonSerivce类的”/hi“方法。由于eureka-client没有响应,判定不可用,开启了熔断器,最后进入了fallbackMethod的逻辑。之后的请求会直接执行fallbackMethod的逻辑。

在Feign上使用熔断器

Feign的起步依赖中已经引入了Hystrix的依赖,只需要在eureka-feign-client工程的配置文件中开启hystrix功能即可,

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

修改EurekaClientFeign代码,在@FeignClient注解的fallback配置加上快速失败的处理类。该处理类是作为geign熔断器的逻辑处理类,必须实现被@FeignClient修饰的接口。

EurekaClientFeign类

@Component
@FeignClient(value = "eureka-client",configuration = FeignConfig.class,fallback = HiHystrix.class)
public interface EurekaClientFeign {
    @GetMapping(value = "/hi")
    String sayHiFromClientEureka(@RequestParam(value = "name")String name);
}

HiHystrix 类

@Component
public class HiHystrix implements EurekaClientFeign {

    @Override
    public String sayHiFromClientEureka(String name) {
        return "hi,"+name+",sorry.error!";
    }
}

FeignConfig类

@Configuration
public class FeignConfig {
    @Bean
    public Retryer feignRetryer(){
        return new Retryer.Default(100,TimeUnit.SECONDS.toMillis(1),5);
    }
}

HiService 类

@Service
public class HiService {
    @Autowired
    EurekaClientFeign eurekaClientFeign;

    public  String sayHi(String name){
        return eurekaClientFeign.sayHiFromClientEureka(name);
    }
}

HiController 类

@RestController
public class HiController {
    @Autowired
    HiService hiService;

    @GetMapping("/hi")
    public String sayHi(@RequestParam(defaultValue = "cralor",required = false)String name){
        return hiService.sayHi(name);
    }
}

启动工程eureka-server、eureka-client和eureka-feign-client,浏览器访问http://localhost:8765/hi

关闭eureka-client

由此可见,当eureka-client不可以时,eureka-feign-client进入了fallback的逻辑处理类HiHystrix,由这个类来执行熔断器打开时的处理逻辑。

使用Hystrix Dashboard监控熔断器的状态

Hystrix Dashboard时监控Hystrix的熔断器的一个组件,提供了数据监控和友好的展示界面。

在Rest Template中使用Hystrix Dashboard

在eureka-ribbon-client工程的pom文件加上Actuator、Hystrix 和Hystrix Dashboard的起步依赖,这三个依赖是必需的。

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

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

        <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>

修改配置文件,启动actuator监控

server:
port: 8764
spring:
application:
name: eureka-ribbon-client
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/

#springboot2.0. 的配置项为:
#actuator端口
management:
server:
port: 9001
endpoints:
web:
# base-path: / #修改访问路径 2.0之前默认是/ 2.0默认是 /actuator 可以通过这个属性值修改
exposure:
include: '*' #开放所有页面节点 默认只开启了health、info两个节点

在程序启动类加上@EnableHystrixDashboard注解,

@EnableHystrixDashboard
@EnableHystrix
@SpringBootApplication
public class EurekaRibbonClientApplication {

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

依次启动eureka-server、eureka-client和eureka-ribbon-client。在浏览器访问先访问http://localhost:8764/hi,然后再访问http://localhost:9001/actuator/hystrix.stream,浏览器会显示熔断器的数据指标

在浏览器访问http://localhost:8764/hystrix,注意:端口号为具体服务对应的端口号而不是Eureka Server的端口号

 

依次填写http://localhost:9001/actuator/hystrix.stream、2000、cralor(随意填写),点击 moniter

 

该页面显示了熔断器的谷中数据指标,这些数据指标含义如图,该图来自于Hystrix官方文档,文档地址:https://github.com/Netflix/Hystrix/wiki

 

 在Feign中使用Hystrix Dashboard

在eureka-feign-client的pom文件加上Actuator、Hystrix和Dashboard的起步依赖,(Feign自带的Hystrix依赖不是起步依赖,还需要加上起步依赖)

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

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

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

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

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

启动类加上注解@EnableHystrixDashboard,@EnableHystrix

@EnableHystrixDashboard
@EnableHystrix
@EnableFeignClients
@SpringBootApplication
public class EurekaFeignClientApplication {

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

启动即可,其他步骤跟ribbon一样。

使用Turbine聚合监控

 在使用Hystrix Dashboard组件监控服务的熔断器状况时,每个服务都有一个Hystrix Dashboard主页,服务数量过多时,监控非常不方便。Netflix开源了另一个组件Turbine,用于聚合多个Hystrix Dashboard,将数据显示在一个页面上,集中监控。

新建一个module工程eureka-monitor-client,作为Turbine聚合监控的工程。pom文件引入相关actuator、hystrix dashboard和turbine的起步依赖

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cralor</groupId>
    <artifactId>eureka-monitor-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>eureka-monitor-client</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>com.cralor</groupId>
        <artifactId>chap8-hystrix</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <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>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

修改配置文件

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

#springboot2.0. 的配置项为:
#actuator端口
management:
#  server:
#    port: 9007
  endpoints:
    web:
#      base-path: /monitor #修改访问路径  2.0之前默认是/   2.0默认是 /actuator  可以通过这个属性值修改
      exposure:
        include: '*'  #开放所有页面节点  默认只开启了health、info两个节点

turbine:
  aggregator:
    cluster-config: default     #需要监控的服务集群名
  app-config: eureka-ribbon-client,eureka-feign-client    #需要监控的服务名
  cluster-name-expression: new String("default")
#  instanceUrlSuffix:
#      default: actuator/hystrix.stream    #key是clusterConfig集群的名字,value是hystrix监控的后缀,springboot2.0为actuator/hystrix.stream

在启动类加上注解

@EnableTurbine
@EnableHystrixDashboard
@SpringBootApplication
public class EurekaMonitorClientApplication {

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

启动工程eureka-server、eureka-client、eureka-ribbon-client、eureka-feign-client和eureka-monitor-client,在浏览器访问http://localhost:8764/hi,http://localhost:8765/hi,在浏览器打开http://localhost:8764/hystrix(端口号8764、8765、8769都可以),依次填入http://localhost:8769/turbine.stream,2000,cralor,点击”monitor“,

可以看到这个页面聚合了eureka-ribbon-client和eureka-feign-client的Hystrix Dashboard数据。

 

参考:https://windmt.com/2018/04/15/spring-cloud-4-hystrix/

https://windmt.com/2018/04/16/spring-cloud-5-hystrix-dashboard/

https://windmt.com/2018/04/17/spring-cloud-6-turbine/

 

 

案例代码地址:https://github.com/cralor7/springcloud

 

 

 

 

posted @ 2018-06-26 18:48  cralor  阅读(9627)  评论(3编辑  收藏  举报