Skip to content

Instantly share code, notes, and snippets.

@jiacai2050
Created June 12, 2018 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jiacai2050/ed5292ca1972871076b6ef8d496c3441 to your computer and use it in GitHub Desktop.
Save jiacai2050/ed5292ca1972871076b6ef8d496c3441 to your computer and use it in GitHub Desktop.
package hystrix;
import com.netflix.hystrix.*;
import rx.Observable;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
public class CommandHelloWorld extends HystrixCommand<String> {
private String name;
public int i;
protected CommandHelloWorld(String name) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ThreadPoolTestGroup"))
.andCommandKey(HystrixCommandKey.Factory.asKey("testCommandKey"))
.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(name))
.andCommandPropertiesDefaults(
HystrixCommandProperties.Setter()
.withCircuitBreakerEnabled(true)//默认是true,本例中为了展现该参数
.withCircuitBreakerForceOpen(false)//默认是false,本例中为了展现该参数
.withCircuitBreakerForceClosed(false)//默认是false,本例中为了展现该参数
.withCircuitBreakerErrorThresholdPercentage(10)//(1)错误百分比超过5%
.withCircuitBreakerRequestVolumeThreshold(10)//(2)10s以内调用次数10次,同时满足(1)(2)熔断器打开
.withCircuitBreakerSleepWindowInMilliseconds(999)//隔2s之后,熔断器会尝试半开(关闭),重新放进来请求
// .withExecutionTimeoutInMilliseconds(1000)
)
.andThreadPoolPropertiesDefaults(
HystrixThreadPoolProperties.Setter()
.withMaxQueueSize(60) //配置队列大小
.withCoreSize(2) // 配置线程池里的线程数
)
);
this.name = name;
}
@Override
protected String run() throws Exception {
Random rand = new Random();
//模拟错误百分比(方式比较粗鲁但可以证明问题)
if (0 == rand.nextInt(2)) {
throw new Exception("make exception");
}
return "ok";
}
@Override
protected String getFallback() {
// System.out.println("FAILBACK");
return "fallback";
}
public static void main(String[] args) {
int numThread = 50;
ExecutorService exec = Executors.newFixedThreadPool(numThread);
for (int t = 0; t < numThread; t++)
exec.submit(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 30; i++) {
CommandHelloWorld helloWorld = new CommandHelloWorld("LC");
try {
Thread.sleep(50);
String s = helloWorld.execute();
System.out.println(String.format("tid[%s] call times: %s, result: %s, circuitBreakerOpen: %s", Thread.currentThread().getName(), i, s, helloWorld.circuitBreaker.isOpen())
);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
}
@juvenn
Copy link

juvenn commented Jun 12, 2018

0 == rand.nextInt(2)

这里有 50% 的概率失败,那就一直不能满足 1, 2 两个条件,所以 open 是正常的?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment