Retry java RestTemplate HTTP request if host offline

前端 未结 3 1631
清酒与你
清酒与你 2020-12-25 13:34

Hi I\'m using the spring RestTemplate for calling a REST API. The API can be very slow or even offline. My application is building the cache by sending thousand

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-25 13:49

    You can also tackle this annotation-driven using Spring Retry. This way you will avoid to implement the template.

    Add it to your pom.xml

    
        org.springframework.retry
        spring-retry
        1.1.2.RELEASE
    
    

    Enable it for your application/configuration

    @SpringBootApplication
    @EnableRetry
    public class MyApplication {
      //...
    }
    

    Guard methods that are in danger of failure with @Retryable

    @Service
    public class MyService {
    
      @Retryable(maxAttempts=5, value = RuntimeException.class, 
                 backoff = @Backoff(delay = 15000, multiplier = 2))
      public List doDangerousOperationWithExternalResource() {
         // ...
      }
    
    }
    

提交回复
热议问题