Spring RetryTemplate return usage

4.7k views Asked by At

For example I've a Spring RetryTemplate configuration:

@Configuration
@EnableRetry
public class RetryTemplateConfig {

    @Bean
    public RetryTemplate retryTemplate() {
        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(5);
        FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
        backOffPolicy.setBackOffPeriod(300000);
        RetryTemplate template = new RetryTemplate();
        template.setRetryPolicy(retryPolicy);
        template.setBackOffPolicy(backOffPolicy);
        return template;
    }
}

And I want to re-invoke this method if exception was caught:

@Scheduled(cron = "${schedule.cron.update}")
    public void calculate() throws Exception {
        log.info("Scheduled started");
        try {
            retryTemplate.execute(retryContext -> {
                myService.work();
                return true;
            });
        } catch (IOException | TemplateException e) {
            log.error(e.toString());
        }
        log.info("Scheduled finished");
    }

So, my method work() in service class can throw exceptions:

 public void send() throws IOException, TemplateException {
        ...
    }

Seems like it works okay, but I really don't understand what does next code mean:

retryTemplate.execute(retryContext -> {
                myService.work();
                return true;
            });

Why I can return true, null, new Object() and other stuff? What it affects and where will it be used? What should i return?

1

There are 1 answers

2
Ori Marko On BEST ANSWER

RetryTemplate executes RetryCallback which is generic and can return any return type you define.

If you need to get data from successful execution you can return it in callback and get it later in flow

Returns: the result of the successful operation.

Example of reading file with retry:

  return template.execute(context -> {
      FileUtils.copyURLToFile(new URL(path), copy);
      return FileUtils.readFileToString(copy, Charset.defaultCharset());