【笔记】Hystrix学习笔记

前言

Hystrix是一个系统容错工具

添加依赖

  • 修改pom.xml配置文件
1
2
3
4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

降级

  • 调用服务器失败(宕机、500错、超时),可以降级执行当前服务中的一段代码,向客户端返回结果,快速失败

  • 在启动类添加@EnableCircuitBreaker注解启用断路器

1
2
3
4
5
6
@EnableCircuitBreaker
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
  • 在调用远程的方法上添加注解@HystrixCommand(),通过fallbackMethod参数指定降级方法名,并添加降级方法
1
2
3
4
5
6
7
8
@HystrixCommand(fallbackMethod = "getItemFB")
@GetMapping("/item-server/{orderId}")
public JsonResult<List<Item>> getItem(@PathVariable String orderId) {
return restTemplate.getForObject("http://item-service/{1}", JsonResult.class, orderId);
}
public JsonResult getItemFB(String orderId) {
return JsonResult.err("出错了");
}

Hystrix超时

  • Hystrix有默认的超时时间为1秒

  • 修改application.yml配置文件

1
2
3
4
5
6
7
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 1000

熔断

  • 当访问量过大,出现大量失败,可以做过热保护,断开远程服务不再调用,实现限流,防止故障传播

  • 断路器打开的条件

    • 10秒内20次请求
    • 50%失败
  • 断路器打开后,直接执行降级代码

  • 断路器打开几秒后,会进入半开状态,客户端调用会尝试向后台服务发送一次调用,如果调用成功,断路器可以自动关闭恢复正常,如果仍然失败,继续保持打开状态几秒钟

  • 加了降级后,无需额外配置,自动开启熔断

故障监控

  • 利用Actuator,来暴露Hystrix的故障日志
  • SpringBoot提供的日志监控工具,可以暴露项目中多种监控信息
    • 健康状态
    • 系统环境变量
    • Spring容器中所有的对象
    • SpringMVC映射的所有路径

健康检查

添加依赖

  • 修改pom.xml配置文件,添加actuator依赖
1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

修改配置

  • 修改application.yml配置文件

*:暴露所有的监控
health:只暴露健康状态
["health","beans","mappings"]:暴露指定的监控
hystrix.stream:hystrix监控

1
2
3
4
5
management:
endpoints:
web:
exposure:
include: "*"

Hystrix Dashboard

添加依赖

  • 修改pom.xml配置文件
1
2
3
4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>

配置

  • 修改application.yml配置文件
1
2
3
4
5
server:
port: 4001
hystrix:
dashboard:
proxy-stream-allow-list: localhost

配置启动类

  • 在启动类添加@EnableHystrixDashboard注解
1
2
3
4
5
6
7
@EnableHystrixDashboard
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

访问仪表盘

  • 访问子路径localhost:4001/hystrix

完成