Hystrix(服务熔断、监控)
Hystrix是由Netflix开源的一个延迟和容错库,用于隔离访问远程系统、服务或者第三方库,防止级联失败,从而提升系统的可用性与容错性。Hystrix主要通过以下几点实现延迟和容错。
- 包裹请求:使用HystrixCommand包裹对依赖的调用逻辑,每个命令在独立线程中执行。这使用
了设计模式中的“命令模式”。 - 跳闸机制:当某服务的错误率超过一定的阈值时,Hystrix可以自动或手动跳闸,停止请求该服务一段时间。
- 资源隔离:Hystrix为每个依赖都维护了一个小型的线程池(或者信号量)。如果该线程池已满,发往该依赖的请求就被立即拒绝,而不是排队等待,从而加速失败判定。
- 监控:Hystrix可以近乎实时地监控运行指标和配置的变化,例如成功、失败、超时、以及被拒绝的请求等。
- 回退机制:当请求失败、超时、被拒绝,或当断路器打开时,执行回退逻辑。回退逻辑由开发人员自行提供,例如返回一个缺省值。
- 自我修复:断路器打开一段时间后,会自动进入“半开”状态。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
- 怎么判断改方法应该被降级?
Hystix的默认超时时长为1s,方法超过1s未返回数据就会被降级
(降级:即不处理用户提交的数据,但给未成功的方法发送提前编写好的数据)
#yml中可以配置超时时间
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 2000
- 指定的降级方法和统一的降级方法
指定的降级方法,通过在Controller方法上使用HystrixCommand注解为该方法指定特定方法
/*使用注解配置熔断保护
* fallbackmethod : 配置熔断之后的降级方法
*/
@HystrixCommand(fallbackMethod = "orderFallBack")
public Product findProduct(@PathVariable Long id) {
...
return product;
}
/**
* 降级方法
* 和需要收到保护的方法的返回值一致
* 方法参数一致
*/
public Product orderFallBack(Long id) {
....
return product;
}
统一的降级方法,就是为这个Controller类中的所有方法指定同一个降级方法。在Controller上使用DefaultProperties注解的defaultFallback指定统一降级方法
@RestController
@RequestMapping("/order")
/**
* @DefaultProperties : 指定此接口中公共的熔断设置
* 如果过在@DefaultProperties指定了公共的降级方法
* 在@HystrixCommand不需要单独指定了
*/
@DefaultProperties(defaultFallback = "defaultFallBack")
public class OrderController {
/**
* 指定统一的降级方法
* * 参数 : 没有参数
*注意返回值,所有方法的返回值都要相同
*/
public Product defaultFallBack() {
Product product = new Product();
product.setProductName("触发统一的降级方法");
return product;
}
//这些方法的降级方法都是defaultFallBack方法
public Product orderFallBack(Long id) {...}
public Product orderFallBack2(Long id) {...}
}
一、 对RestTemplate支持
- 配置依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
-
在启动类OrderApplication 中添加@EnableCircuitBreaker 注解开启对熔断器的支持
@EnableCircuitBreaker //开启熔断器 @SpringBootApplication public class OrderApplication { //创建RestTemplate对象 @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); } }
ps:也可以使用
@SpringCloudApplication
代替.注解@SpringCloudApplication包括:@SpringBootApplication、@EnableDiscoveryClient、@EnableCircuitBreaker,分别是SpringBoot注解、注册服务中心Eureka注解、断路器注解。(使用@SpringCloudApplication需要导入2个pom的dependency:spring-cloud-starter-eureka和spring-cloud-starter-hystrix)
3.在Controller中配置熔断降级业务逻辑
- 编写熔断的降级逻辑方法
- 在需要被降级的方法上使用HystrixCommand(fallbackMethod = “findProductFallBack”) 用来声明一个降级逻辑的方法
@RestController @RequestMapping("/order") public class OrderController { @Autowired private RestTemplate restTemplate; @GetMapping("/product/{id}") //2>声明HystrixCommand @HystrixCommand(fallbackMethod = "orderFallBack") public Product findProduct(@PathVariable Long id) { return restTemplate.getForObject("http://shop-serviceproduct/ product/1", Product.class); } // 1>降级方法 public Product orderFallBack(Long id) { Product product = new Product(); product.setId(-1l); product.setProductName("熔断:触发降级方法"); return product; } }
二、对Feign支持
springcloud-Hystrix已经集成了feign,无需再导入依赖
1.修改application.yml在Fegin中开启hystrix
- spring-cloud版本2020.0.0的断路器开启配置
#application.yml # 启动feign的断路器Hystrix feign: circuitbreaker: enabled: true
#配置feign日志的输出 #日志配置 NONE : 不输出日志(高) BASIC: 适用于生产环境追踪问题 #HEADERS : 在BASIC的基础上,记录请求和响应头信息 FULL : 记录所有 feign: client: config: service-product: #需要调用的服务名称 loggerLevel: FULL
-
配置FeignClient接口的实现类
本来feign调用其他微服务就是通过自写接口, FeignClient注解指定需要调用的微服务名称,然后Controller方法调用这个接口中方法。 (Feign详见这一篇 https://blog.csdn.net/qq_43220949/article/details/112453174)
//指定需要调用的微服务名称
@FeignClient(name="service-product")
public interface ProductFeignClient {
//调用的请求路径
@RequestMapping(value = "/product/{id}",method = RequestMethod.GET)
public Product findById(@PathVariable("id") Long id);
}
支持Hystrix,需要配置FeignClient接口的实现类,接口实现类中编写熔断降级方法.
/**
* 实现自定义的ProductFeginClient接口
* 在接口实现类中编写熔断降级方法
*/
@Component
public class ProductFeginClientCallBack implements ProductFeginClient {
/**
* 降级方法
*/
public Product findById(Long id) {
Product product = new Product();
product.setId(-1l);
product.setProductName("熔断:触发降级方法");
return product;
}
}
- 在自写的FeignClient接口 中的@FeignClient注解中添加降级方法。
@FeignClient注解中以fallback声明降级方法类.class
//FeignClient注解中fallback声明降级方法类.class
@FeignClient(name="shop-service-product",fallback =
ProductFeginClientCallBack.class)
public interface ProductFeginClient {
//调用的请求路径
@RequestMapping(value = "/product/{id}",method = RequestMethod.GET)
public Product findById(@PathVariable("id") Long id);
}
附1、Hystrix监控信息:实时的监控
HystrixCommand和HystrixObservableCommand在执行时,会生成执行结果和运行指标。比如每秒的请求数量,成功数量等。
A.数据流监控 http://localhost:9001/actuator/hystrix.stream
- 导入hystrix监控pom依赖
<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>
- 在SpringApplication启动类添加EnableHystrixDashboard 注解
//EnableHystrixDashboard
@EnableHystrixDashboard
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
- 在application.yml中配置 暴露所有actuator监控的端点
management:
endpoints:
web:
exposure:
include: '*'
访问 http://localhost:9001/actuator/hystrix.stream 即可看到实时的监控数据流。
B.DashBoard监控
1.导入hystrix监控pom依赖
和上边的依赖一样
<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注解激活仪表盘项目
@EnableHystrixDashboard
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
访问http://localhost:9003/hystrix
C.断路器聚合监控Turbine
Turbine是一个聚合Hystrix 监控数据的工具,他可以将所有相关微服务的
Hystrix 监控数据聚合到一起,方便使用。
在微服务架构体系中,每个服务都需要配置Hystrix DashBoard监控。如果每次只能查看单个实例的监控数据,就需要不断切换监控地址,这显然很不方便。要想看这个系统的Hystrix Dashboard数据就需要用到Hystrix Turbine。
- 单独构建一个工程模块服务,导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-turbine</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>
- 配置多个微服务的hystrix监控
在application.yml的配置文件中开启turbine并进行相关配置,哪个服务需要被监控就在 turbine.appConfig中配置上,使用逗号隔开。
server:
port: 8031
spring:
application:
name: microservice-hystrix-turbine
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/ #指定注册中心地址
instance:
prefer-ip-address: true
turbine:
# 要监控的微服务列表,多个用,分隔
appConfig: shop-service-order
clusterNameExpression: "'default'"
turbine会自动的从注册中心中获取需要监控的微服务,并聚合所有微服务中的/hystrix.stream 数据
- 配置启动类
@SpringBootApplication
//开启HystrixDashboard监控平台,并激活Turbine
@EnableTurbine
@EnableHystrixDashboard
public class TurbineServerApplication {
public static void main(String[] args) {
SpringApplication.run(TurbineServerApplication.class, args);
}
}
浏览器访问 http://localhost:8031/hystrix 展示HystrixDashboard。并在url位置输入 <a href="http://localhost:8031/turbine.stream>http://localhost:8031/turbine.stream,动态根据turbine.stream数据展示多个微服务的监控数据
附2、断路器
熔断器(断路器)有三个状态 CLOSED 、OPEN 、HALF_OPEN(半开) 。
熔断器默认关闭状态,当触发熔断后状态变更为OPEN ,在等待到指定的时间,Hystrix会放请求检测服务是否开启,这期间熔断器会变为HALF_OPEN 半
开启状态,熔断探测服务可用,则继续变更为 CLOSED 关闭熔断器。
Closed:断路器关闭,即微服务可以正常访问。
Open:当一定时间内失败请求百分比达到阈值,则触发熔断,微服务的请求直接进入降级方法。默认失败比例的阈值是50%,请求次数最少不低于20次。
Half -Open:半开。open状态不是永久的,打开后会进入休眠时间(默认是5S),即半开状态。 半开状态会释放1次请求通过,若这个请求是健康的,则会关闭断路器,否则继续保持打开,再次进行5秒休眠计时。
circuitBreaker.requestVolumeThreshold=5 #触发熔断的最小请求次数,默认20
circuitBreaker.sleepWindowInMilliseconds=10000 #熔断多少秒后去尝试请求
circuitBreaker.errorThresholdPercentage=50 #触发熔断的失败请求最小占比,默认50%
hystrix:
command:
default:
execution:
isolation:
strategy: #配置隔离策略
ExecutionIsolationStrategy.SEMAPHORE #信号量隔离
# ExecutionIsolationStrategy.THREAD 线程池隔离
maxConcurrentRequests: 10 #最大信号量上限
项目源码:https://gitee.com/hxmkd/spring-cloud/tree/master/study_springcloud5_hystrix