目的
优雅地处理服务失效,防止雪崩
功能
(1)隔离失效服务。服务使用单独的线程池,当服务失效太多后被熔断,不调用该服务,从而无法影响其余服务。
(2)服务降级。当服务失效后,提供降级的处理方法。
(3)快速失败。可以设置时延,设置熔断条件,以达到快速失效,不会一直耗着资源。
(4)监控面板
什么时候会熔断
达到熔断条件(timeout、窗口时间内最大失败个数、窗口时间内失败比率等),熔断后会在circuitBreakerSleepWindowInMilliseconds内不再调用该服务,过了这个设时间,则会变成半开状态,尝试重新请求,再次失败后回到断开状态。
什么时候会调用降级方法
(1)抛出异常
(2)达到熔断条件
(3)线程池拒绝
原生方式:
(1)继承HystrixCommand/HystrixObservableCommand
(2)重写run()/construct()
(3)实例化
(4)执行execute()/queue()/observe()/toObservable()。
public class LblCommand extends HystrixCommand<String>{
protected LblCommand() {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
}
@Override
protected String run() throws Exception {
throw new Exception();
}
@Override
protected String getFallback() {
return "fallback";
}
}
Spring cloud方式:
1. 创建项目,包含hystrix依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2.主类中开启熔断器
@SpringBootApplication
@EnableCircuitBreaker
public class HystrixApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixApplication.class, args);
}
}
3.使用注解声明HystrixCommand,注意不可以在同一个类中调用HystrixCommand注解的方法,否则不会生效。
@Component
public class LblCommand2 {
@HystrixCommand(fallbackMethod = "myfallback",commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")})
String testHystrix(int i) throws Exception{
System.out.println(new Date().getSeconds() + ":tried");
if(i == 0){
return "success";
}
throw new Exception();
//Thread.sleep(2000);
//return "success";
}
@HystrixCommand
String myfallback(int i){
return "fallback!";
}
}