Spring Boot 2关于Async的使用
入口类加上注解@EnableAsync
@SpringBootApplication
@EnableAsync
@ComponentScan(basePackages = {"XXX.XX.XXX"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
在调用方法加上注解@Async
@Async
@Override
public Future<String> getAsync1() {
return new AsyncResult<String>(ChineseNameUtil.getChineseName());
}
@Async("asyncTaskExecutor")
@Override
public void process1() {
ChineseNameUtil.getChineseName();
}
自定义线程池
- 这里需要用ThreadPoolTaskExecutor,这里可以设置线程池的各种参数,但是不能自定义处理后台线程异常
private enum Singleton {
INSTANCE;
private ThreadPoolTaskExecutor taskExecutor = null;
Singleton() {
taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
taskExecutor.setMaxPoolSize(20);
taskExecutor.setQueueCapacity(2000);
taskExecutor.setThreadNamePrefix("TEST_");
taskExecutor.initialize();
}
public ThreadPoolTaskExecutor getInstance() {
return taskExecutor;
}
}
- 实现接口AsyncConfigurer,可以针对异步异常进行处理
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (ex, method, params) -> logger.error("*****AsyncUncaughtExceptionHandler:方法:{},参数:{},错误:{}", method.getDeclaringClass().getName() + "." + method.getName(), getParams(params), ExceptionUtil.getExceptionStack(ex));
}
源码位置
https://gitee.com/ceclar123/spring-boot-demo/tree/master/ch04