SpringBoot自定义线程池异步执行任务
@EnableAsync
@Configuration
public class MyAsyncConfigurer implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(Integer.MAX_VALUE);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setThreadNamePrefix("myTaskExecutor-");
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new MyAsyncExceptionHandler();
}
}
@Slf4j
public class MyAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
@Override
public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
log.info("------全局线程池异常处理-----");
log.info("------error fillInStackTrace:" + throwable.fillInStackTrace());
log.info("------error message:" + throwable.getMessage());
log.info("------error methodName:" + method.getName());
for (Object param : objects)
{
log.info("------param:" + param);
}
}
}
@Component
public class MyTask {
@Scheduled(cron = "0/5 * * * * ?")
@Async
public void task1() {
System.out.println("------静态定时任务1" + Thread.currentThread().getId() + "------" +
Thread.currentThread().getName() + "调度:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
@Scheduled(cron = "0/10 * * * * ?")
@Async
public void task2() {
System.out.println("------静态定时任务2" + Thread.currentThread().getId() + "------" +
Thread.currentThread().getName() + "调度:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
}