springboot项目配置
1、application.properties 线程池基本属性值配置:
threadpool.corePoolSize=10
threadpool.maxPoolSize=50
threadpool.queueCapacity=300
threadpool.keepAliveSeconds=1000
threadpool.threadNamePrefix="elk-"
2、Application启动类上面加开启异步注解@EnableAsync
@SpringBootApplication
@EnableAsync
public class ElkApplication {
public static void main(String[] args) {
SpringApplication.run(ElkApplication.class, args);
}
}
3、ThreadPoolProperties属性值配置
@Data
@Component
@ConfigurationProperties(prefix = "threadpool")
public class ThreadPoolProperties {
private Integer corePoolSize;
private Integer maxPoolSize;
private Integer queueCapacity;
private Integer keepAliveSeconds;
private String threadNamePrefix;
}
4、ThreadPoolTaskConfig线程池创建配置
@Configuration
public class ThreadPoolTaskConfig {
@Autowired
private ThreadPoolProperties threadPoolProperties;
@Bean
public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
executor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());
executor.setThreadNamePrefix(threadPoolProperties.getThreadNamePrefix());
// 线程池对拒绝任务的处理策略 - 调用的线程执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 初始化
executor.initialize();
return executor;
}
}
5、异步线程调用
@GetMapping
public void get() {
System.out.println("1");
threadPoolTaskExecutor.execute(()->
log.info("执行线程:{}",Thread.currentThread().getName())
);
for (int i = 0; i < 10; i++) {
System.out.println("2");
}
threadPoolTaskExecutor.execute(()->
log.info("执行线程:{}",Thread.currentThread().getName())
);
System.out.println("3");
}