ThreadPoolTaskConfig:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
@ConfigurationProperties(prefix = "executor.thread")
public class ThreadPoolTaskConfig{
private static final Logger logger = LoggerFactory.getLogger(ThreadPoolTaskConfig.class);
private Integer corePoolSize;
private Integer maxPoolSize;
private Integer keepAliveSeconds;
private Integer queueCapacity;
private String threadNamePrefix;
@Bean(name = "threadPoolTask")
public Executor executor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程数
executor.setCorePoolSize(this.corePoolSize);
//最大线程数
executor.setMaxPoolSize(this.maxPoolSize);
//核心线程外的线程存活时间秒
executor.setKeepAliveSeconds(this.keepAliveSeconds);
//队列大小
executor.setQueueCapacity(this.queueCapacity);
//线程名称前缀
executor.setThreadNamePrefix(this.threadNamePrefix);
//拒绝策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallRunsPolicy());
executor.initializer();
logger.info("=======线程池创建成功=======");
return executor;
}
//get set方法,手打太累了,记得补全下;
public Integer getCorePoolSize() {return corePoolSize;}
public void setCorePoolSize(Integer corePoolSize) {this.corePoolSize=corePoolSize;}
}
yml文件配置:
###################
# 线程池
###################
executor:
thread:
core-pool-size: 25
max-pool-size: 30
keep-alive-seconds: 300
queue-capacity: 5
thread-name-prefix: thread-name
使用线程池:
//针对你业务需要用到的方法添加注解@Async
//例:
@Async(value = "threadPoolTask")
public void word(Map<String,Object> map){
}