Create the class MyAsyncConfig
Inheriting AsyncConfigurer allows for more detailed configuration, thread pools, and exception handling classes.
@Configuration
@EnableAsync
@Log4j
public class MyAsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadNamePrefix("Anno-Executor");
// Maximum number of threads
executor.setMaxPoolSize(10);
// Core thread
executor.setCorePoolSize(5);
// Queue size
executor.setQueueCapacity(999);
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60 * 15);
executor.initialize();
return executor;
}
// Configure the exception handling class
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new AsyncUncaughtExceptionHandler() {
@Override
public void handleUncaughtException(Throwable ex, Method method, Object. params) {
log.info("Exception message - " + ex.getMessage());
log.info("Method name - " + method.getName());
for (Object param : params) {
log.info("Parameter value - "+ param); }}}; }}Copy the code
The business layer AsyncService
To start asynchronous execution, add @async to the method and print the thread ID. @async (name=” “)
@Service
public class AsyncService {
private static final Logger log = LoggerFactory.getLogger(AsyncService.class);
/** * the simplest asynchronous call, returns void */
@Async
public void asyncInvokeSimplest() {
log.info("asyncSimplest{}",Thread.currentThread().getId());
}
/** * Asynchronous calls to asynchronous methods with arguments can pass in arguments **@param s* /
@Async
public void asyncInvokeWithParameter(String s) {
log.info("asyncInvokeWithParameter, parementer={}", s);
log.info("{}",Thread.currentThread().getId());
throw new IllegalArgumentException(s);
}
/** * The exception call returns Future **@param i
* @return* /
@Async
public Future<String> asyncInvokeReturnFuture(int i) {
log.info("asyncInvokeReturnFuture, parementer={}", i);
log.info("{}",Thread.currentThread().getId());
Future<String> future;
try {
future = new AsyncResult<String> ("success:" + i);
} catch (Exception e) {
future = new AsyncResult<String> ("error");
}
returnfuture; }}Copy the code
Start the test class
@Autowired
private AsyncService asyncService;
@Test
public void asynTest() throws ExecutionException, InterruptedException {
asyncService.asyncInvokeSimplest();
asyncService.asyncInvokeWithParameter("test");
Future<String> future = asyncService.asyncInvokeReturnFuture(100);
System.out.println(future.get());
}
Copy the code