概述
- hystrix 断路器工具,提供了系统容错功能。在Spring Cloud 中一般不单独使用,通常使用
feign
和zuul
集成。
配置
1、添加 hystrix 依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2、主程序配置
- 添加
@EnableCircuitBreaker
注解
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
@EnableDiscoveryClient 启用断路器
@SpringBootApplication
public class Sp06RibbonApplication {
public static void main(String[] args) {
SpringApplication.run(Sp06RibbonApplication.class, args);
}
}
3、配置超时时间(可不配)
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 1000
降级功能
- 方法快速失败,返回指定的降级内容
实现降级方法
- 在指定的方法上添加
@HystrixCommand(fallbackMethod = "降级方法名")
注解
@HystrixCommand(fallbackMethod = "getItemsFB")
@GetMapping("/item-service/{orderId}")
public JsonResult<List<Item>> getItems(@PathVariable String orderId) {
return restTemplate.getForObject("http://item-service/{1}", JsonResult.class, orderId);
}
// 降级方法
public JsonResult<List<Item>> getItemsFB(@PathVariable String orderId) {
return JsonResult.err("获取订单商品列表失败");
}
熔断功能
- 在实现降级后,默认就会有熔断功能
熔断的条件:
- 1、10秒20次请求(必须首先满足)
- 2、50% 的请求失败,执行降级代码
半开状态:
- 在打开断路器后,每隔5秒就会变成 半开状态 ,会尝试发送一次请求,成功,自动关闭断路器,失败,断路器继续打开
Hystrix dashboard
- Spring Cloud 中的监控工具,利用
actuator
暴露监控数据
添加 actuator
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- 暴露的监控端点为:hystrix.stream
yml配置
management:
endpoints:
web:
exposure:
include: hystrix.stream
使用 dashboard监控 暴露的端点
新建一个项目
- 1、添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
- 2、在主程序上添加
@EnableHystrixDashboard
注解
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
@EnableHystrixDashboard
@SpringBootApplication
public class Sp08HystrixDashboardApplication {
public static void main(String[] args) {
SpringApplication.run(Sp08HystrixDashboardApplication.class, args);
}
}
1、先测试是否成功暴露端点
- http://localhost:3001/actuator/hystrix.stream
在没有访问后台服务的时候,只显示ping
只有访问后台服务后才有监控数据
访问 Hystrix dashboard
- http://localhost:4001/hystrix
把暴露的端口地址复制到1处,点击 2 开始监控
从左到右,从上往下代表的次数分别为成功,短路,错误请求,超时,拒绝,失败错误
Circuit 显示断路器的状态,open为打开,closed为关闭