Skip to content

Instantly share code, notes, and snippets.

@mguilherme
Last active June 26, 2017 01:16
Show Gist options
  • Save mguilherme/a6ea06e364a6ad3eba41a35986e5d761 to your computer and use it in GitHub Desktop.
Save mguilherme/a6ea06e364a6ad3eba41a35986e5d761 to your computer and use it in GitHub Desktop.
jodah Failsafe with Spring task executor
package com.guilherme.miguel.failsafe;
import lombok.extern.slf4j.Slf4j;
import net.jodah.failsafe.Failsafe;
import net.jodah.failsafe.RetryPolicy;
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.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author Miguel Guilherme
*/
@Slf4j
@SpringBootApplication
public class FailsafeRetry {
public static void main(String[] args) {
SpringApplication.run(FailsafeRetry.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(MyService myService) {
return args -> execute(myService);
}
@Bean
public AsyncTaskExecutor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
executor.setThreadNamePrefix("myExecutor-");
return executor;
}
private void execute(MyService myService) {
RetryPolicy retryPolicy = new RetryPolicy()
.withDelay(2, TimeUnit.SECONDS)
.withMaxRetries(3);
asyncExecutor().execute(() ->
Failsafe.with(retryPolicy)
.onFailedAttempt((o, throwable, context) ->
log.warn("Retrying, Message: {}, Attempt: {}", throwable.getMessage(), context.getExecutions())
)
.onFailure(throwable -> log.error("Failure, {}", throwable.getMessage()))
.withFallback(() -> null)
.run(() -> myService.doStuff())
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment