2

我正在使用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()
}


我希望重试重试所有异常。

4

1 回答 1

0

您正在创建装饰供应商,该供应商只捕获RuntimeExceptionsConnectException不是RuntimeException

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

浏览Retry.java并选择一个例如捕获ExceptiondecorateCheckedFunction,例如

  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

我个人使用softwaremill/retry

于 2019-06-25T12:26:14.067 回答