Async (Spring Boot)
Introduction
Asynchronous execution in Spring Boot and the @Async annotation.
See also 'Retry (Spring Boot)' post:
https://sites.google.com/site/pawneecity/sprint-boot/retry-spring-boot
References
Using Spring boot Async with Retry
https://www.openprogrammer.info/2019/09/03/using-spring-boot-async-with-retry/
Java 8 Parallel Processing With Completable Future
https://dzone.com/articles/java-8-parallel-processing-with-completable-future
Guide To CompletableFuture
https://www.baeldung.com/java-completablefuture
Enable, configurer and exception handler
package edu.cou.myapp;
import java.lang.reflect.Method;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import lombok.extern.slf4j.Slf4j;
/**
* Asynchronous processing.
*/
@Slf4j
@EnableAsync
@Configuration
public class AsyncConfig implements AsyncConfigurer, AsyncUncaughtExceptionHandler {
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
// DOC Instance of the functional interface AsyncUncaughtExceptionHandler
return this;
}
@Override
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
log.warn("----------------INI CustomAsyncExceptionHandler----------------");
log.warn("Method name: " + method.getName());
for (Object px : params) {
log.warn("Parameter value: " + px);
}
log.warn("Exception message: " + ex.getMessage(), ex);
log.warn("----------------END CustomAsyncExceptionHandler----------------");
}
}
Misc.
>>> Return type of an @Async method
The return type must be void or java.util.concurrent.Future
>>> Timeout for async method
String result = futureResult.get(1, TimeUnit.SECOND);