4.断路器是否打开
在命令结果没有缓存命中的时候,Hystrix在执行命令前需要检查断路器是否为打开状态:
如果断路器是打开的,那么Hystrix不会执行命令,而是转接到fallback处理逻辑
如果断路器是关闭的,那么Hystrix调到第5步(线程池/请求队列/信号量是否占满),检查是否有可用资源来执行命令
断路器开启:
1.整个链路达到一定的阈值,默认情况下,10秒内产生超过20次请求,则符合第一个条件
2.满足第一个条件的情况下,如果请求的错误百分比大于阈值,则会打开断路器,默认50%
public class OpenMain {
public static void main(String[] args) {
//10秒内有10次请求满足第一个条件
ConfigurationManager.getConfigInstance().setProperty(
"hystrix.command.default.circuitBreaker.requestVolumeThreshold",10);
for(int i=0;i<15;i++){
ErrorCommand c=new ErrorCommand();
String result=c.execute();
System.out.println(result);
System.out.println(c.isCircuitBreakerOpen());
}
}
static class ErrorCommand extends HystrixCommand<String>{
public ErrorCommand(){
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(500)));
}
protected String run() throws InterruptedException{
Thread.sleep(800);
return "success";
}
protected String getFallback(){
return "fallback";
}
}
}
public class CloseMain {
public static void main(String[] args) throws InterruptedException {
ConfigurationManager.getConfigInstance().setProperty(
"hystrix.command.default.circuitBreaker.requestVolumeThreshold",3);
boolean isTimeout=true;
for(int i=0;i<10;i++){
TestCommand c=new TestCommand(isTimeout);
c.execute();
System.out.println(c.isCircuitBreakerOpen());
HealthCounts hc=c.getMetrics().getHealthCounts();
System.out.println("健康信息:"+hc.getTotalRequests());
if(c.isCircuitBreakerOpen()){
isTimeout=false;
System.out.println("------------断路器打开了,等待休眠期结束");
Thread.sleep(6000);
}
}
}
static class TestCommand extends HystrixCommand<String>{
private boolean isTimeout;
public TestCommand(boolean isTimeout){
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(500)));
this.isTimeout=isTimeout;
}
protected String run() throws InterruptedException{
if(isTimeout){
Thread.sleep(800);
}else{
Thread.sleep(200);
}
return "";
}
protected String getFallback(){
return "fallback";
}
}
}