package com.guilherme.miguel.retry; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.retry.RetryCallback; import org.springframework.retry.RetryContext; import org.springframework.retry.RetryListener; import org.springframework.retry.annotation.EnableRetry; import org.springframework.retry.annotation.Recover; import org.springframework.retry.annotation.Retryable; import org.springframework.retry.backoff.FixedBackOffPolicy; import org.springframework.retry.listener.RetryListenerSupport; import org.springframework.retry.policy.SimpleRetryPolicy; import org.springframework.retry.support.RetryTemplate; import org.springframework.stereotype.Service; @Slf4j @EnableRetry @SpringBootApplication public class SpringRetry { public static void main(String[] args) { SpringApplication.run(SpringRetry.class, args); } @Bean public RetryTemplate retryTemplate() { SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(); retryPolicy.setMaxAttempts(5); FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy(); backOffPolicy.setBackOffPeriod(1500); // 1.5 seconds RetryTemplate template = new RetryTemplate(); template.setRetryPolicy(retryPolicy); template.setBackOffPolicy(backOffPolicy); template.registerListener(new CustomRetryListener()); return template; } @Bean public CommandLineRunner commandLineRunner(RetryTemplate retryTemplate, SomeService someService, OtherService otherService) { return args -> { // With annotations someService.someMethod(); // RetryTemplate retryTemplate.execute(context -> { otherService.otherMethod(); return null; }, context -> { log.error("Recovering from {}", context.getLastThrowable().getMessage()); return null; }); }; } @Service public class SomeService { @Retryable public void someMethod() { log.info("Executing some method"); throw new RuntimeException("some runtime exception"); } @Recover public void recover(Exception e) { log.error("Recovering from {}", e.getMessage()); } } @Service public class OtherService { public void otherMethod() { log.info("Executing other method"); throw new RuntimeException("other runtime exception"); } } public class CustomRetryListener extends RetryListenerSupport { @Override public void onError(RetryContext context, RetryCallback callback, Throwable throwable) { log.warn("Retrying..."); super.onError(context, callback, throwable); } } } // Maven dependencies for Spring Retry: // // org.springframework.boot // spring-boot-starter-aop // // // org.springframework.retry // spring-retry //