我正在尝试将重试策略与具有 Failsafe 的 CircuitBreaker 模式相结合,但是当尝试在电路打开并中断时出现 CircuitBreakerOpenException 异常。
https://github.com/jhalterman/failsafe
问题是通过将重试延迟设置为小于电路的关闭时间而产生的。
如何控制此异常,使重试策略不中断?我想这样做是因为我可以让多个同时实例向休息服务发起请求,并且重试不会中断。
我的代码:
public class UnstableApplication {
private final int MAX_FAILS = 4;
private AtomicInteger failCount = new AtomicInteger(1);
public String generateId() throws Exception {
if (failCount.getAndIncrement() < MAX_FAILS) {
System.err.printf("UnstableApplication throws SampleException at '%s'\n", ZonedDateTime.now());
throw new Exception();
}
final String id = UUID.randomUUID().toString();
System.out.printf("UnstableApplication: id '%s' generated at '%s'\n", id, ZonedDateTime.now());
return id;
}
}
public class FailsafeExample {
public static void main(String[] args) throws Exception {
UnstableApplication app = new UnstableApplication();
RetryPolicy retryPolicy = new RetryPolicy()
.retryOn(Exception.class)
.withDelay(2, TimeUnit.SECONDS)
.withMaxRetries(5);
CircuitBreaker breaker = new CircuitBreaker();
breaker.withFailureThreshold(2);
breaker.withDelay(5, TimeUnit.SECONDS);
breaker.withSuccessThreshold(3);
breaker.onOpen(() -> {
System.out.println("Circuit breaker is open");
});
breaker.onClose(() -> {
System.out.println("Circuit breaker is close");
});
breaker.onHalfOpen(() -> {
System.out.println("Circuit breaker is half-close");
});
Failsafe.with(retryPolicy)
.with(breaker)
.onFailedAttempt((a, b) -> {
System.out.println(
String.format("Failed with exception: %s, at %s, circuit-breaker state is: %s",
b, ZonedDateTime.now(), breaker.getState()));
})
.onSuccess(cxn -> {
System.out.println("Succcess!");
})
.onFailure(cxn -> {
System.out.println("Failed!");
})
.get(new Callable<String>() {
@Override
public String call() throws Exception {
return app.generateId();
}
});
}
}
我的结果:
UnstableApplication throws SampleException at '2019-05-31T16:30:09.214Z[Etc/UTC]'
Failed with exception: java.lang.Exception, at 2019-05-31T16:30:09.221Z[Etc/UTC], circuit-breaker state is: CLOSED
UnstableApplication throws SampleException at '2019-05-31T16:30:11.229Z[Etc/UTC]'
Circuit breaker is open
Failed with exception: java.lang.Exception, at 2019-05-31T16:30:11.230Z[Etc/UTC], circuit-breaker state is: OPEN
Exception in thread "main" net.jodah.failsafe.CircuitBreakerOpenException
at net.jodah.failsafe.SyncFailsafe.call(SyncFailsafe.java:136)
at net.jodah.failsafe.SyncFailsafe.get(SyncFailsafe.java:56)
at com.kash.test.Foo.main(Foo.java:63)