英文:
Resilience4j returning a CompletableFuture around tried method
问题
boolean void syncMethod() throws Exception {
// 可能由于连接/授权问题抛出异常。
}
CompletableFuture<Boolean> asyncResilience4jWrapper() {
CompletableFuture<Boolean> result =
...
在 "syncMethod()" 周围使用 Resilience4j 魔法。
尝试调用 4 次,调用之间间隔 100 毫秒。
...;
return result;
}
英文:
I can't find out how to wrap a synchronous method with Resilience4j so that it returns a CompletableFuture, although this seems to be part of Resilience4j's target area.
Especially since the synchronous method I want to wrap can throw an Exception.
What I want in pseudo code:
<!-- language: lang-java -->
boolean void syncMethod() throws Exception {
// May throw Exception due to connection/authorization problems.
}
CompletableFuture<Boolean> asyncResilience4jWrapper() {
CompletableFuture<Boolean> result =
...
Resilience4j magic around "syncMethod()".
Trying 4 calls, interval between calls of 100 ms.
...;
return result;
}
Resilience4j should just try to call the method 4 times until it gives up, with intervals between the calls of 100 ms and then complete the asynchronous call.
The asyncResilience4jWrapper caller should just get back a CompletableFuture which doesn't block and don't care about any of that.
答案1
得分: 4
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);
TimeLimiter timeLimiter = TimeLimiter.of(Duration.ofSeconds(1));
CompletableFuture<Boolean> future = Decorators.ofCallable(() -> syncMethod)
.withThreadPoolBulkhead(threadPoolBulkhead)
.withTimeLimiter(timeLimiter, scheduledExecutorService)
.withCircuitBreaker(circuitBreaker)
.withFallback(asList(TimeoutException.class, CallNotPermittedException.class, BulkheadFullException.class),
throwable -> "Hello from Recovery")
.withRetry(retry) // Add this line
.get().toCompletableFuture();
英文:
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);
TimeLimiter timeLimiter = TimeLimiter.of(Duration.ofSeconds(1));
CompletableFuture<Boolean> future = Decorators.ofCallable(() -> syncMethod)
.withThreadPoolBulkhead(threadPoolBulkhead)
.withTimeLimiter(timeLimiter, scheduledExecutorService)
.withCircuitBreaker(circuitBreaker)
.withFallback(asList(TimeoutException.class, CallNotPermittedException.class, BulkheadFullException.class),
throwable -> "Hello from Recovery")
.get().toCompletableFuture();
Just add withRetry
below the CircuitBreaker.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论