前言
在肖项目模块中,我们可能会优先考虑到使用spring自带的定时任务Schedule,但是schedule默认是单线程的,在执行任务中,串行执行的效果肯定是比异步执行慢的,在定时任务的配置类中SchedulingConfigurer下面有一个configureTasks方法,我们可以在里面配置定时任务的异步线程池,但是开发中的异步不止有定时任务,一般类似导入/导出结果的也会使用的异步线程池。我们可以在一个配置类中再继承一个AsyncConfigurer接口
SchedulingConfigurer和AsyncConfigurer的联合使用
代码如下(示例):
SchedulingConfigurer的configureTasks方法
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setTaskScheduler(taskScheduler());
}
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setThreadNamePrefix("Task-Thread-");
taskScheduler.setPoolSize(taskPoolSize);
taskScheduler.setAwaitTerminationSeconds(6000000);
taskScheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
taskScheduler.setWaitForTasksToCompleteOnShutdown(false);
taskScheduler.setDaemon(true);
return taskScheduler;
}
AsyncConfigurer的getAsyncExecutor和getAsyncUncaughtExceptionHandler
@Override
public Executor getAsyncExecutor() {
return asyncTaskExecutor();
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (Throwable throwable, Method method, Object... objs) -> {
// log.error("异步任务发生错误: 方法名: {}", method.getName());
throwable.printStackTrace();
};
}
@Bean
public AsyncTaskExecutor asyncTaskExecutor() {
ThreadPoolTaskExecutor asyncTaskExecutor = new ThreadPoolTaskExecutor();
asyncTaskExecutor.setThreadNamePrefix("Async-Thread-");
asyncTaskExecutor.setCorePoolSize(3);
asyncTaskExecutor.setQueueCapacity(100);
asyncTaskExecutor.setMaxPoolSize(asyncPoolSize);
asyncTaskExecutor.setKeepAliveSeconds(keepAliveSeconds);
asyncTaskExecutor.setAllowCoreThreadTimeOut(true);
asyncTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
asyncTaskExecutor.setWaitForTasksToCompleteOnShutdown(false);
return asyncTaskExecutor;
}