1

我不知道如何用 Resilience4j 包装同步方法,以便它返回 CompletableFuture,尽管这似乎是 Resilience4j目标区域的一部分。特别是因为我要包装的同步方法可以抛出异常。我想要的伪代码:

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 应该只尝试调用该方法 4 次直到它放弃,调用之间的间隔为 100 毫秒,然后完成异步调用。asyncResilience4jWrapper 调用者应该只取回一个 CompletableFuture ,它不会阻塞并且不关心任何这些。

4

1 回答 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")
    .get().toCompletableFuture();

只需withRetry在断路器下方添加即可。

于 2020-05-29T12:35:01.033 回答