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?
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
Example of reading file with retry: