【框架】SpringBoot中自定义线程池
时间:2021-01-18 14:33:33
收藏:0
阅读:331
自定义线程池
SpringBoot中对线程池的自定义分为两种:
- 修改默认的线程池
- 创建新的自定义线程池
1. 修改默认的线程池
修改默认的线程池,需要创建配置类:
- 加入两个注解:
@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()
}
};
}
}
2. 创建新的自定义线程池
直接在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"
:无论是否修改过默认线程池,都使用修改前的默认配置- 自定义线程池类名:使用指定的自定义线程池,注意这里是类名(即注册为Bean的名字)
- 不填 或
@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
评论(0)