使用 resilience4j 重试不适用于某些例外情况

Retry with resilience4j doesn't work with some exceptions

我正在使用 resilience4j 库重试一些代码,下面有以下代码,我希望它 运行 4 次。如果我抛出 IllegalArgumentException 它会工作,但如果我抛出 ConnectException 它就不会。

object Test extends App {

  val retryConf = RetryConfig.custom()
    .maxAttempts(4)
    .retryOnException(_ => true)
    //.retryExceptions(classOf[ConnectException])
    .build
  val retryRegistry = RetryRegistry.of(retryConf)
  val retryConfig = retryRegistry.retry("test", retryConf)
  val supplier: Supplier[Unit] = () => {
    println("Run")
    throw new IllegalArgumentException("Test")
    //throw new ConnectException("Test")
  }

  val decoratedSupplier = Decorators.ofSupplier(supplier).withRetry(retryConfig).get()
}


我希望重试所有异常。

您正在创建 decorated supplier,它只捕获 RuntimeExceptionsConnectException 不是 RuntimeException:

    ... decorateSupplier(Retry retry, Supplier<T> supplier) {
        return () -> {
            Retry.Context<T> context = retry.context();
            do try {
               ...
            } catch (RuntimeException runtimeException) {
               ...

翻阅Retry.java and choose one that catches Exception for example decorateCheckedFunction,例如

  val registry = 
    RetryRegistry.of(RetryConfig.custom().maxAttempts(4).build())
  val retry = registry.retry("my")

  Retry.decorateCheckedFunction(retry, (x: Int) => {
    println(s"woohoo $x")
    throw new ConnectException("Test")
    42
  }).apply(1)

输出

woohoo 1
woohoo 1
woohoo 1
woohoo 1
Exception in thread "main" java.rmi.ConnectException: Test

我个人使用