hystrix的回退机制大概如下图所示:
1:测试hystrix熔断配置:
#设置断路器的状态是false
ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.circuitBreaker.forceOpen","false");
#设置触发断路器开关的时间:10s ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.metrics.rollingStats.timeInMilliseconds.",10000);
#设置时间内,请求数达到3次。打开断路器 ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.circuitBreaker.requestVolumeThreshold",3);
#设置时间10s.请求次数3次。失败率达到50%。打开断路器 ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.circuitBreaker.errorThresholdPercentage",50);
#断路器打开后。休眠三秒不在请求实际服务。三秒后再次请求 ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds",3000);
boolean isTimeOut = true;
for(int i=0;i<20;i++){
FallbackCommandB fallbackCommand = new FallbackCommandB(isTimeOut);
fallbackCommand.execute();
HystrixCommandMetrics.HealthCounts healthCounts = fallbackCommand.getMetrics().getHealthCounts();
System.out.println("断路器的状态:"+fallbackCommand.isCircuitBreakerOpen()+"总请求的数量:"+healthCounts.getTotalRequests());
if(fallbackCommand.isCircuitBreakerOpen()){
//断路器是开的
isTimeOut = false;
System.out.println("断路器是开着的,等待休眠结束");
Thread.sleep(4000);
}
}
定义回退:
static class FallbackCommandB extends HystrixCommand<String> {
private boolean isTimeOut;
public FallbackCommandB(boolean isTimeOut){
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroupB")).andCommandPropertiesDefaults(
HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(500)
));
this.isTimeOut = isTimeOut;
}
@Override
protected String run() throws Exception {
System.out.println("执行命令2..");
if(isTimeOut){
System.out.println("断路器关着后来再开着。这里把断路器关掉");
Thread.sleep(800);
}else{
System.out.println("断路器关着。如果到达临界阈值就会打开断路器");
Thread.sleep(300);
}
return null;
}
protected String getFallback() {
System.out.println("执行回调2..");
return "fallback";
}
}
执行结果:
可以看到第四次请求的时候。断路器状态就打开了。休眠三秒后。再次请求打印:执行命令2.成功了。所以断路器就再次关掉了