1

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:

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.

Jan
  • 1,032
  • 11
  • 26

1 Answers1

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();

Just add withRetry below the CircuitBreaker.

Robert Winkler
  • 1,734
  • 9
  • 8
  • I forgot to mention that I need it for a method with a parameter, turns out that this is really different, so I just posted a second question for that. https://stackoverflow.com/questions/62147297/resilience4j-returning-a-completablefuture-around-tried-method-with-parameter – Jan Jun 02 '20 at 07:53