【问题标题】:Retry with resilience4j doesn't work with some exceptions使用resilience4j 重试不适用于某些异常
【发布时间】:2019-06-25 11:56:09
【问题描述】:

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


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

【问题讨论】:

    标签: java scala resilience4j


    【解决方案1】:

    您正在创建 decorated supplier,它只会捕获 RuntimeExceptions,而 ConnectException 不是 RuntimeException

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

    查看Retry.java 并选择一个捕获Exception 的,例如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
    

    我个人使用softwaremill/retry

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      • 2014-12-17
      • 2013-06-26
      • 2021-07-30
      • 1970-01-01
      相关资源
      最近更新 更多