Retry java RestTemplate HTTP request if host offline

前端 未结 3 1593
清酒与你
清酒与你 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

    <dependency>
        <groupId>org.springframework.retry</groupId>
        <artifactId>spring-retry</artifactId>
        <version>1.1.2.RELEASE</version>
    </dependency>
    

    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<String> doDangerousOperationWithExternalResource() {
         // ...
      }
    
    }
    
    0 讨论(0)
  • 2020-12-25 14:06

    I had same situation and done some googling found the solution. Giving answer in hope it help someone else. You can set max try and time interval for each try.

    @Bean
      public RetryTemplate retryTemplate() {
    
        int maxAttempt = Integer.parseInt(env.getProperty("maxAttempt"));
        int retryTimeInterval = Integer.parseInt(env.getProperty("retryTimeInterval"));
    
        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(maxAttempt);
    
        FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
        backOffPolicy.setBackOffPeriod(retryTimeInterval); // 1.5 seconds
    
        RetryTemplate template = new RetryTemplate();
        template.setRetryPolicy(retryPolicy);
        template.setBackOffPolicy(backOffPolicy);
    
        return template;
      }
    

    And my rest service that i want to execute is below.

    retryTemplate.execute(context -> {
            System.out.println("inside retry method");
            ResponseEntity<?> requestData = RestTemplateProvider.getInstance().postAsNewRequest(bundle, ServiceResponse.class, serivceURL,
                    CommonUtils.getHeader("APP_Name"));
    
            _LOGGER.info("Response ..."+ requestData);
                throw new IllegalStateException("Something went wrong");
            });
    
    0 讨论(0)
  • 2020-12-25 14:07

    Use Spring Retry project (https://dzone.com/articles/spring-retry-ways-integrate, https://github.com/spring-projects/spring-retry).

    It is designed to solve problems like yours.

    0 讨论(0)
提交回复
热议问题