本文共 1719 字,大约阅读时间需要 5 分钟。
支持Spring Boot中使用@Async注解进行异步线程处理@Async注解会启用独立线程池执行方法,无法被@RestControllerAdvice捕获异步方法的异常处理需要手动实现package com.common.base.config;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 org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;import java.lang.reflect.Method;import java.util.concurrent Executor;/** * @Author: tony_t_peng * @Date: 2020-08-10 10:06 * * 支持使用@Async注解进行异步线程处理 * @Async方法将在独立线程池中执行 * 该线程池由本配置类管理,无法被@ControllerAdvice全局异常处理器捕获 * 异常处理需要手动实现 */@Configuration@EnableAsyncpublic class BaseAsyncConfigurer implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(Runtime.getRuntime().availableProcessors()); executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 5); executor.setQueueCapacity(Runtime.getRuntime().availableProcessors() * 2); executor.setThreadNamePrefix("this-excutor-"); executor.initialize(); return executor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return (Throwable ex, Method method, Object... params) -> { System.out.println("class#method: " + method.getDeclaringClass().getName() + "#" + method.getName()); System.out.println("type : " + ex.getClass().getName()); System.out.println("exception : " + ex.getMessage()); }; }}
转载地址:http://cjqfk.baihongyu.com/