SpringBoot中对线程池的自定义分为两种:
修改默认的线程池,需要创建配置类:
@EnableAsync
开启异步执行功能@Configuration
Spring配置类AsyncConfigurer
接口,并实现两个方法:
public Executor getAsyncExecutor()
:注意在返回Executor
必须初始化executor.initialize()
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler()
/** 修改默认线程池 */
@Slf4j
@EnableAsync
@Configuration
public class AsyncPoolConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程池大小
executor.setCorePoolSize(10);
//最大线程数
executor.setMaxPoolSize(20);
//队列容量
executor.setQueueCapacity(20);
//活跃时间
executor.setKeepAliveSeconds(60);
//线程名字前缀
executor.setThreadNamePrefix("AsyncPool_");
// 拒绝策略
executor.setRejectedExecutionHandler(
new ThreadPoolExecutor.CallerRunsPolicy()
);
// 停机是否等待任务
executor.setWaitForTasksToCompleteOnShutdown(true);
// 停机等待任务的最大时长
executor.setAwaitTerminationSeconds(60);
// 线程池初始化
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new AsyncUncaughtExceptionHandler(){
@Override
public void handleUncaughtException(Throwable throwable,
Method method,
Object... objects) {
throwable.printStackTrace();
log.error("AsyncError: {}, Method: {}",
throwable.getMessage(), method.getName()
}
};
}
}
直接在Spring配置类中创建返回Executor
的方法,并加上@Bean
注解注册为Bean。
@Configuration
public class MyAsyncPool {
@Bean
public Executor MyAsyncPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程池大小
executor.setCorePoolSize(10);
//最大线程数
executor.setMaxPoolSize(20);
//队列容量
executor.setQueueCapacity(20);
//活跃时间
executor.setKeepAliveSeconds(60);
//线程名字前缀
executor.setThreadNamePrefix("MyAsyncPool_");
// 拒绝策略
executor.setRejectedExecutionHandler(
new ThreadPoolExecutor.CallerRunsPolicy()
);
// 停机是否等待任务
executor.setWaitForTasksToCompleteOnShutdown(true);
// 停机等待任务的最大时长
executor.setAwaitTerminationSeconds(60);
executor.initialize();
return executor;
}
}
在需要开启异步执行的方法上,加入两个注解:
@Scheduled(fixedRate = 3*1000)
fixedRate
单位为毫秒@Async(value)
开启异步执行,这里的参数分为几种情况:
""
:采用默认的线程池,如果修改过默认线程池,则使用修改过的配置"taskScheduler"
:无论是否修改过默认线程池,都使用修改前的默认配置@Slf4j
@Component
public class Task {
@Scheduled(fixedRate = 3*1000)
@Async("MyAsyncPool")
public void cleanExpiredTemplate_(){
log.info(Thread.currentThread().getName() + ": Task is finished");
}
}
原文:https://www.cnblogs.com/BWSHOOTER/p/14292200.html