Hystrix的使用-断路器(二)
1、断路器开启
- 整个链路达到一定的阀值,默认情况下,10秒内产生超过20次请求,则符合第一个条件
- 满足第一个条件的情况下,如果请求的错误百分比大于阀值,则会开启断路器,默认为50%(如:10内发送30次请求,其中15次是失败的,则会开启断路器)
package com.atm.cloud.open;
import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
public class OpenMain {
public static void main(String[] args) {
ConfigurationManager
.getConfigInstance()
.setProperty(
"hystrix.command.default.circuitBreaker.requestVolumeThreshold",
10);
for (int i = 0; i < 15; i++) {
ErrorCommand c = new ErrorCommand();
c.execute();
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)));
}
@Override
protected String run() throws Exception {
Thread.sleep(800);
return "";
}
@Override
protected String getFallback() {
return "fallback";
}
}
}
2、断路器关闭
- 当断路器打开的时候,不再执行命令,直接进行回退方法,这段时间称为休眠期,默认时间为5s
- 休眠期结束之后,会尝试性执行一次命令,此时,断路器状态处于半开状态,尝试执行成功之后,就会关闭断路器并且清空健康信息,如果失败,仍然处于关闭状态
package com.atm.cloud.open;
import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandMetrics.HealthCounts;
import com.netflix.hystrix.HystrixCommandProperties;
public class CloseMain {
public static void main(String[] args) throws Exception {
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();
HealthCounts hc = c.getMetrics().getHealthCounts();
System.out.println("断路器状态:" + c.isCircuitBreakerOpen() + ", 请求数量:"
+ 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;
}
@Override
protected String run() throws Exception {
if (isTimeout) {
Thread.sleep(800);
} else {
Thread.sleep(200);
}
return "";
}
@Override
protected String getFallback() {
return "fallback";
}
}
}