设置全局异步线程池类
问题背景
项目里经常使用线程可以设置全局异步线程池
线程池设置类
1 实现AsyncConfigurer方法,配置异步线程池
package com.adayun.dataxcompute.config;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
// 异步配置线程池参数,线程前缀名 AsyncThread-
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程数
executor.setCorePoolSize(60);
//最大线程数
executor.setMaxPoolSize(120);
//队列容量,默认使用无限队列
executor.setQueueCapacity(500);
//线程不工作的保活时间
executor.setKeepAliveSeconds(60);
//设置线程名字前缀
executor.setThreadNamePrefix("AsyncThread-");
//拒绝策略,用调用者所在的线程来执行任务
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//60s之后强制关闭
executor.setAwaitTerminationSeconds(60);
//等待全部线程结束进行关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}
总结
每次使用@Async就可以使用线程池的核心线程,减少创建资源的开销
作为程序员第 119 篇文章,每次写一句歌词记录一下,看看人生有几首歌的时间,wahahaha …
Lyric: 我已经跟不上
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/110756.html