Resilience4j在尝试的方法周围返回一个CompletableFuture。

huangapple go评论123阅读模式
英文:

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&lt;Boolean&gt; asyncResilience4jWrapper() {
	CompletableFuture&lt;Boolean&gt; result = 
		...
			Resilience4j magic around &quot;syncMethod()&quot;. 
			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&lt;Boolean&gt; future = Decorators.ofCallable(() -&gt; syncMethod)
    .withThreadPoolBulkhead(threadPoolBulkhead)
    .withTimeLimiter(timeLimiter, scheduledExecutorService)
    .withCircuitBreaker(circuitBreaker)
    .withFallback(asList(TimeoutException.class, CallNotPermittedException.class, BulkheadFullException.class),
      throwable -&gt; &quot;Hello from Recovery&quot;)
    .withRetry(retry) // Add this line
    .get().toCompletableFuture();
英文:
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);
TimeLimiter timeLimiter = TimeLimiter.of(Duration.ofSeconds(1));

CompletableFuture&lt;Boolean&gt; future = Decorators.ofCallable(() -&gt; syncMethod)
    .withThreadPoolBulkhead(threadPoolBulkhead)
    .withTimeLimiter(timeLimiter, scheduledExecutorService)
    .withCircuitBreaker(circuitBreaker)
    .withFallback(asList(TimeoutException.class, CallNotPermittedException.class, BulkheadFullException.class),
      throwable -&gt; &quot;Hello from Recovery&quot;)
    .get().toCompletableFuture();

Just add withRetry below the CircuitBreaker.

huangapple
  • 本文由 发表于 2020年5月29日 18:46:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/62084143.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定