测试目标
在指定配置内达到根据配置进行熔断,以下是测试代码
/*
* Copyright (C) 2005 - 2030 YGSoft.Inc All Rights Reserved.
* YGSoft.Inc PROPRIETARY/CONFIDENTIAL.Use is subject to license terms.
*/
package teng.sv.server.springgateway.tsf.test;
import com.netflix.hystrix.*;
import java.util.concurrent.TimeUnit;
/**
* 线程池隔离.
*
* @author luyong
* @since JDK 1.8
*/
public class HystrixThreadPool_V2 extends HystrixCommand<String> {
/**
* name.
*/
private final String name;
/**
* 构造器.
*
* @param name
*/
public HystrixThreadPool_V2(String name) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(name))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionTimeoutInMilliseconds(5000)
// 滚动窗口期有超过指定数量错误就熔断,没达到错误数前,发生错误时会再调用回调,达到了就直接熔断,不再调业务方法以,直接熔断到回调。
.withCircuitBreakerRequestVolumeThreshold(4)
// .withCircuitBreakerErrorThresholdPercentage(50)
// 每10秒为一个窗口期
.withCircuitBreakerSleepWindowInMilliseconds(10000)
.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
).andThreadPoolPropertiesDefaults(
HystrixThreadPoolProperties.Setter().withCoreSize(1)
)
);
/*
HystrixCommandProperties
.Setter()
.withExecutionTimeoutEnabled(true)
.withFallbackEnabled(false)
.withRequestCacheEnabled(false)
.withRequestLogEnabled(false)
// .withCircuitBreakerEnabled(true)
.withCircuitBreakerErrorThresholdPercentage(100)
.withCircuitBreakerRequestVolumeThreshold(10).withMetricsRollingStatisticalWindowInMilliseconds(10000)
.withMetricsRollingPercentileEnabled(false)
.withExecutionTimeoutInMilliseconds(12000)
.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD);
*/
this.name = name;
}
/**
* 运行方法.
*
* @return
* @throws Exception
*/
@Override
protected String run() throws Exception {
System.out.println("run "+name);
TimeUnit.MILLISECONDS.sleep(1000);
// CacheOperationUtil.getSession("testToken", "testName");
if(1>0) {
throw new Exception("test exception");
}
return name;
}
/**
* 回调方法.
*
* @return
*/
@Override
protected String getFallback() {
return "fallback: " + name;
}
}
单元测试方法
@Test
public void testCicurbreak() {
for (int i = 0; i < 30; i++) {
try {
String result = new HystrixThreadPool_V2("thread pool-"+i).execute();
System.out.println(result);
} catch (Exception e) {
System.out.println("run()抛出HystrixBadRequestException时,被捕获到这里" + e.getCause());
}
}
// command指标信息
for (HystrixCommandMetrics metrics : HystrixCommandMetrics.getInstances()) {
boolean isCircuitOpen = HystrixCircuitBreaker.Factory.getInstance(metrics.getCommandKey()).isOpen();
lgger.info("group:{}, commandKey:{}, CircuitOpen:{}, Mean:{}, 95%:{}, 99%:{}, 99.5%:{}, {}",
metrics.getCommandGroup().name(),
metrics.getCommandKey().name(),
isCircuitOpen,
metrics.getExecutionTimeMean(),
metrics.getExecutionTimePercentile(95.0),
metrics.getExecutionTimePercentile(99.5),
metrics.getExecutionTimePercentile(99.5),
metrics.getHealthCounts()
);
Assert.assertEquals(true, isCircuitOpen);
}
}
scg解析路由时的filterFactory

评论区