spring boot 自定义线程池与使用
一、进行线程池创建
import cn.hutool.core.thread.ThreadFactoryBuilder; import lombok.extern.slf4j.Slf4j; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.AsyncConfigurerSupport; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import java.lang.reflect.Method; import java.util.concurrent.Executor; /** * 线程池配置(异步线程) */ @Slf4j @Configuration @EnableAsync public class ThreadPoolTaskSchedulerConfig extends AsyncConfigurerSupport { @Bean("threadPoolTaskScheduler") public ThreadPoolTaskScheduler threadPoolTaskScheduler() { //这里使用的为定时任务线程池,替代@Scheduled注解,进行动态定时任务配置 ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setThreadFactory(ThreadFactoryBuilder.create().build()); scheduler.setPoolSize(60); scheduler.setRemoveOnCancelPolicy(true); scheduler.setThreadNamePrefix("TASK-SCHEDULE-"); scheduler.initialize(); return scheduler; } @Override public Executor getAsyncExecutor() { return threadPoolTaskScheduler(); } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return (Throwable t, Method m, Object... args) -> { log.error("=============================" + t.getMessage() + "=============================="); log.error("threadPoolTaskScheduler exception Method:" + m.getName()); }; } }