1 前言
- 我们知道,当请求失败,被拒绝,超时的时候,都会进入到降级方法中。但是进入降级方法并不意味着断路器已经被打开了。此时我们需要Hystrix的监控平台来查看断路器的状态。
2 Hystrix的监控平台
2.1 概述
- 除了实现容错功能,Hystrix还提供了近乎实时的监控,HystrixCommand和HystrixObervableCommand在执行的时候,会生成执行结果和运行指标。比如每秒的请求数量、成功数量等待。这些状态会暴露在Actuator提供的/health端点中。
- 导入相关jar包的Maven坐标:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><!-- openfeign --><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>
- 在启动类上开启Hystrix:
package com.sunxiaping;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;import org.springframework.cloud.openfeign.EnableFeignClients;@SpringBootApplication@EnableFeignClients //开启OpenFeign的支持@EnableCircuitBreaker //开启Hystrixpublic class Order9007Application {public static void main(String[] args) {SpringApplication.run(Order9007Application.class, args);}}
- 在application.yml中将所有的端点打开:
# 配置hystrixhystrix:command:default:execution:isolation:thread:timeoutInMilliseconds: 6000 # 默认的连接超时时间为1秒,如果1秒没有返回数据,就自动触发降级逻辑feign:hystrix: # 开启Feign中的Hystrixenabled: true# 暴露所有端点management:endpoints:web:exposure:include: '*'

2.2 搭建Hystrix DashBoard监控
- Hystrix官方提供了基于图形化的DashBoard(仪表盘)监控平台,用来直观的展示系统的运行状态。Hystrix仪表盘可以显示每个断路器的状态。
- 导入依赖:
<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</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId></dependency>
- 在启动类上添加@EnableHystrixDashboard注解以激活仪表盘:
package com.sunxiaping;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;import org.springframework.cloud.openfeign.EnableFeignClients;@SpringBootApplication@EnableFeignClients //开启OpenFeign的支持@EnableCircuitBreaker //开启Hystrix@EnableHystrixDashboard // 激活仪表盘public class Order9007Application {public static void main(String[] args) {SpringApplication.run(Order9007Application.class, args);}}
- 重启项目,访问http://localhost:9007/hystrix,输入监控端点(http://localhost:9007/actuator/hystrix.stream)展示监控的详细数据。

2.3 断路器聚合监控Turbine
2.3.1 概述
- 在微服务架构体系中,每个服务都需要配置Hystrix DashBoard监控。如果每次只能查看单个实例的监控数据,就需要不断切换监控地址,这显然很不方便。要想看整个系统的Hystrix DashBoard数据就需要用到Hystrix Turbine。Turbine是一个聚合Hystrix监控数据的工具,它可以将所有相关微服务的Hystrix监控数据聚合到一起,方便使用,引入Turbine后,整个监控系统架构如下:

2.3.2 搭建Turbine Server
创建一个工程,并引入相关jar包的Maven坐标:
- 修改部分:
<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-hystrix</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-turbine</artifactId></dependency>
- 完整部分:
<?xml version="1.0" encoding="UTF-8"?><project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://maven.apache.org/POM/4.0.0"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>spring_cloud_demo</artifactId><groupId>org.sunxiaping</groupId><version>1.0</version></parent><modelVersion>4.0.0</modelVersion><artifactId>hystrix_turbine7004</artifactId><dependencies><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-hystrix</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-web</artifactId></dependency></dependencies></project>
配置多个微服务的hystrix监控。
- 在application.yml的配置文件中开启turbine并进行相关配置:
server:port: 7004spring:application:name: service-turbine # 微服务的名称# 配置 eurekaeureka:instance:# 主机名称:服务名称修改,其实就是向eureka server中注册的实例idinstance-id: service-turbine:${server.port}# 显示IP信息prefer-ip-address: trueclient:service-url: # 此处修改为 Eureka Server的集群地址defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/turbine:# 要监控的微服务列表,多个用,隔开app-config: service-ordercluster-name-expression: "'default'"
配置启动类:
package com.sunxiaping.turbine;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;import org.springframework.cloud.netflix.turbine.EnableTurbine;@SpringBootApplication@EnableHystrixDashboard@EnableTurbinepublic class Turbine7004Application {public static void main(String[] args) {SpringApplication.run(Turbine7004Application.class, args);}}
浏览器访问http://localhost:7004/hystrix展示Hystrix DashBoard,并在URL的位置输入http://localhost:7004/turbine.stream,可能会出现如下的错误:

- 需要在SpringBoot中配置HystrixMetricsStreamServlet:
package com.sunxiaping.config;import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class SpringConfig {@Beanpublic ServletRegistrationBean getServlet() {HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);registrationBean.setLoadOnStartup(1);registrationBean.addUrlMappings("/hystrix.stream");registrationBean.setName("HystrixMetricsStreamServlet");return registrationBean;}}
3 断路器的状态
3.1 概述
- 断路器的状态有三种:
CLOSED、OPEN和HALF_OPEN。断路器默认CLOSED状态,当触发熔断后状态变更为OPEN状态,在等待指定的时间,Hystrix会放请求检测服务是否开启,这期间断路器的状态会由OPEN状态变为HALF_OPEN状态,一旦探测服务可用则将断路器的状态由HALF_OPEN变为CLOSED来关闭断路器。

- CLOSED:关闭状态,所有请求都能够正常访问。代理类维护了最近调用失败的次数,如果某次调用失败,则失败次数加1。如果最近失败次数超过了在给定时间内允许失败的阈值,则代理类切换到OPEN(打开)状态。此时代理开启了一个超时时钟,当该时钟超过了该时间,则切换到HALF_OPEN(半打开)状态。该超时是吉恩的设定给了系统一次机会来修正导致调用失败的错误。
- OPEN:打开状态,所有请求都会被降级。Hystrix会对请求情况计数,当一定时间内失败请求百分比达到阈值,则触发熔断,断路器完全关闭。默认失败比例的阈值是50%,请求次数最少不低于20次。
- HALF_OPEN:半打开状态,OPEN的状态不是永久的,打开后进行休眠时间(默认是5秒)。随后断路器会自动进入半打开状态,此时会释放一个请求通过,如果这个请求是健康的,则关闭断路器,否则继续保持打开,再次进行5秒休眠计时。
总结:
Hystrix正常启动的时候,断路器的状态是CLOSED状态(所有的请求都可以正常访问)。
默认情况下,当请求次数大于20次,且存在50%的失败概率的时候,将自动触发熔断,断路器的状态变为OPEN状态(所有的请求都会进入到降级方法中)。
默认情况下,会维持OPEN状态一段时间(5s),进入到半打开状态(尝试释放一个请求到远程微服务发起调用)。如果释放的请求可以正常访问,就会关闭断路器(断路器的状态由HALF_OPEN状态变为CLOSED状态)。如果释放的请求不能访问,则将状态由HALF_OPEN状态变为OPEN状态。
3.2 测试断路器的工作状态
3.2.1 环境准备
- ①在订单系统中加入如下的逻辑:
判断请求的id,如果id=1,正常执行(正常调用微服务)。
判断请求的id,如果id!=1,抛出异常。
- ②默认Hystrix有断路器状态转化的阈值。
触发熔断的最小请求次数为20次。
触发熔断的请求失败比例为50%。
断路器开启的时长为5秒。
3.2.2 修改订单系统的逻辑
- OrderController.java
package com.sunxiaping.order.controller;import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;import com.sunxiaping.order.domain.Product;import com.sunxiaping.order.feign.ProductFeignClient;import lombok.var;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.client.RestTemplate;@RestController@RequestMapping(value = "/order")public class OrderController {@Autowiredprivate RestTemplate restTemplate;@Autowiredprivate ProductFeignClient productFeignClient;@GetMapping(value = "/buy/{id}")@HystrixCommand(fallbackMethod = "orderFallback", commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"), //默认的连接超时时间为1秒,如果1秒内没有返回数据,自动触发降级逻辑})public Product buy(@PathVariable(value = "id") Long id) {if (1 != id) {throw new RuntimeException("服务器异常");}return restTemplate.getForObject("http://SERVICE-PRODUCT/product/findById/" + id, Product.class);}public Product orderFallback(Long id) {var product = new Product();product.setId(Long.MAX_VALUE);product.setProductName("******测试断路器的状态******");return product;}}
3.2.3 修改Hystrix有断路器状态转化的阈值
- 修改方式一:@HystrixCommand注解中配置
package com.sunxiaping.order.controller;import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;import com.sunxiaping.order.domain.Product;import com.sunxiaping.order.feign.ProductFeignClient;import lombok.var;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.client.RestTemplate;@RestController@RequestMapping(value = "/order")public class OrderController {@Autowiredprivate RestTemplate restTemplate;@Autowiredprivate ProductFeignClient productFeignClient;@GetMapping(value = "/buy/{id}")@HystrixCommand(fallbackMethod = "orderFallback", commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"), //默认的连接超时时间为1秒,如果1秒内没有返回数据,自动触发降级逻辑@HystrixProperty(name = "circuitBreaker.enabled", value = "true"), //是否开启断路器@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "5"), //触发熔断的最小请求次数,默认为20/10秒@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), //熔断多少秒后去尝试请求,默认为10秒@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"), //触发熔断的失败请求最小比例,默认为50%})public Product buy(@PathVariable(value = "id") Long id) {if (1 != id) {throw new RuntimeException("服务器异常");}return restTemplate.getForObject("http://SERVICE-PRODUCT/product/findById/" + id, Product.class);}public Product orderFallback(Long id) {var product = new Product();product.setId(Long.MAX_VALUE);product.setProductName("******测试断路器的状态******");return product;}}
- 修改方式二:修改application.yml
hystrix:command:default:execution:isolation:thread:timeoutInMilliseconds: 3000 # 默认的连接超时时间为1秒,如果1秒没有返回数据,就自动触发降级逻辑circuitBreaker:requestVolumeThreshold: 5 #触发熔断的最小请求次数,默认20/10秒sleepWindowInMilliseconds: 10000 #熔断多少秒后去尝试请求,默认为10秒errorThresholdPercentage: 50 #触发熔断的失败请求最小占比,默认50%
4 断路器的隔离策略
- 微服务使用Hystrix熔断器实现了服务的自动降级,让微服务具备自我保护的能力,提升了系统的稳定性,也较好的解决了雪崩效应。其使用方式目前支持两种策略:
线程池隔离策略:使用一个线程池来存储当前的请求,线程池对请求进行处理,设置任务返回处理超时时间,堆积的请求入线程池队列。这种方式需要为每个依赖的服务申请线程池队列,有一定的资源消耗,好处是可以应对突发流量(流量洪峰来临时,处理不玩可以将数据存储到线程池队列慢慢处理)。信号量隔离策略:使用一个原子计数器(或信号量)来记录当前有多少个线程在运行,请求过来先判断计数器的数值,如果超过设置的最大线程个数则丢弃该类型的新请求,如果不超过设置的最大线程个数则将计数器+1,请求返回计数器-1。这种方式是严格控制线程且立即返回模式,无法应对突发流量(流量洪峰来临时,处理的线程超过数量,其他的请求会直接返回,不继续去请求依赖的服务)。 | | 线程池隔离 | 信号量隔离 | | —- | —- | —- | | 线程 | 与调用线程非相同线程 | 与调用线程相同(jetty线程) | | 开销 | 排队、调度、上下文开销等 | 无线程切换,开销低 | | 异步 | 可以是异步,也可以是同步。看调用的方法 | 同步调用,不支持异步 | | 并发支持 | 支持(最大线程池大小hystrix.threadpool.default.maximumSize) | 支持(最大信号量上限maxConcurrentRequests) | | 是否超时 | 支持,可直接返回 | 不支持,如果阻塞,只能通过调用协议(如:socket超时才能返回) | | 是否支持熔断 | 支持,当线程池到达maxSize后,再请求会触发fallback接口进行熔断 | 支持,当信号量达到maxConcurrentRequests后。再请求会触发fallback | | 隔离原理 | 每个服务单独用线程池 | 通过信号量的计数器 | | 资源开销 | 大,大量线程的上下文切换,容易造成机器负载高 | 小,只是个计数器 |
- 可以通过在application.yml中配置隔离策略:
hystrix:command:default:execution:isolation:strategy: ExecutionIsolationStrategy.SEMAPHORE # 信号量隔离maxConcurrentRequests: 5000 # 最大信号量上限# strategy: ExecutionIsolationStrategy.THREAD # 线程池隔离
