本文节选自《疯狂Spring Cloud微服务架构实战》
京东购买地址::https://item.jd.com/12256011.html
当当网购买地址::http://product.dangdang.com/25201393.html
Spring Cloud教学视频:http://blog.youkuaiyun.com/boxiong86/article/details/78399104
Spring Cloud电子书:http://blog.youkuaiyun.com/boxiong86/article/details/78488226
18 Hystrix断路器的开启和关闭
断路器开启
断路器一旦开启,就会直接调用回退方法,不再执行命令,而且也不会更新链路的健康状况。断路器的开启要满足两个条件:
1、整个链路达到一定的阀值,默认情况下,10秒内产生超过20次请求,则符合第一个条件。
2、满足第一个条件的情况下,如果请求的错误百分比大于阀值,则会打开断路器,默认为50%。
Hystrix的逻辑,先判断是否满足第一个条件,再判断第二个条件,如果两个条件都满足,则会开启断路器。断路器开启的测试代码,请见代码清单6-8。
代码清单6-8:
codes\06\6.2\first-hnystrix-client\src\main\java\org\crazyit\cloud\breaker\OpenTest.java
public class OpenTest {
public static void main(String[] args) throws Exception {
// 10秒内有10个请求,则符合第一个条件
ConfigurationManager.getConfigInstance().setProperty(
"hystrix.command.default.metrics.rollingStats.timeInMilliseconds", 10000);
ConfigurationManager.getConfigInstance().setProperty(
"hystrix.command.default.circuitBreaker.requestVolumeThreshold", 10);
ConfigurationManager.getConfigInstance().setProperty(
"hystrix.command.default.circuitBreaker.errorThresholdPercentage", 50);
for(int i = 0; i <15; i++) {
//执行的命令全部都会超时
MyCommand c = new MyCommand();
c.execute();
//断路器打开后输出信息
if(c.isCircuitBreakerOpen()) {
System.out.println("断路器被打开,执行第" + (i + 1) + " 个命令");
}