前言
快速上手
第一步新增依赖:hystrix-core 或者 spring-cloud-starter-netflix-hystrix
<!-- https://mvnrepository.com/artifact/com.netflix.hystrix/hystrix-core -->
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>1.5.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.2.10.RELEASE</version>
</dependency>
第二步:
主启动类添加 @EnableHystrix
新增注解@HystrixCommand(defaultFallback = “fallback1”) 并指定降级方法。
@HystrixCommand(defaultFallback = "fallback1")
@GetMapping("b2")
public String b2() {
int a = 1 / 0;
return "this is b2 ...";
}
public String fallback1() {
return "this is fallback b...";
}
可以看到成功返回降级方法内容
HystrixCommand
public @interface HystrixCommand {
String groupKey() default "";
String commandKey() default "";
String threadPoolKey() default "";
String fallbackMethod() default "";
HystrixProperty[] commandProperties() default {};
HystrixProperty[] threadPoolProperties() default {};
Class<? extends Throwable>[] ignoreExceptions() default {};
ObservableExecutionMode observableExecutionMode() default ObservableExecutionMode.EAGER;
HystrixException[] raiseHystrixExceptions() default {};
String defaultFallback() default "";
}
指定等待时间
方法1s返回结果,超过500直接返回降级方法。
@HystrixCommand(fallbackMethod = "fallback2", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "500")
})
@GetMapping("c")
public String c() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "this is c ...";
}
public String fallback2() {
return "this is fallback c...";
}
hystrix-dashboard
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix-dashboard -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
<version>2.2.10.RELEASE</version>
</dependency>
新增注解@EnableHystrixDashboard
访问路径 /hystrix
效果图
示例地址 https://localhost:8094/actuator/hystrix.stream
@EnableCircuitBreaker 和 @EnableHystrix 区别
在2.2.10版本中 EnableCircuitBreaker 被标记为过时的,且 EnableHystrix 和 EnableCircuitBreaker 作用是相同的,EnableHystrix 直接使用了 EnableCircuitBreaker 注解。
EnableCircuitBreaker
核心注解
@Import(EnableCircuitBreakerImportSelector.class)
知识点
节选自官网版本2.2.10.RELEASE
spring:
cloud:
circuitbreaker:
hystrix:
enabled: false