2

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

boolean void syncMethod(Parameter param) throws Exception {
    // May throw Exception due to connection/authorization problems.
}

CompletableFuture<Boolean> asyncResilience4jWrapper() {
    CompletableFuture<Boolean> result = 
        ...
            Resilience4j magic around "syncMethod(param)". 
            Trying 4 calls, interval between calls of 100 ms. 
        ...;
    return result;
}

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

真正困难的部分似乎是让它为带有参数的方法运行,抛出异常!

4

1 回答 1

0

做就是了

CompletableFuture<Boolean> asyncResilience4jWrapper(Parameter param) {
   return CompletableFuture<Boolean> future = Decorators.ofCallable(() -> syncMethod(param))
    .withThreadPoolBulkhead(threadPoolBulkhead)
    .withTimeLimiter(timeLimiter, scheduledExecutorService)
    .withCircuitBreaker(circuitBreaker)
    .withRetry(retry)
    .withFallback(asList(TimeoutException.class, CallNotPermittedException.class, BulkheadFullException.class),
      throwable -> "Hello from Recovery")
    .get().toCompletableFuture();
}
于 2020-06-02T11:42:39.840 回答