spring boot使用自定义配置的线程池执行使用自定义配置的线程池执行Async异步任务异步任务
主要介绍了spring boot使用自定义配置的线程池执行Async异步任务,小编觉得挺不错的,现在分享给大家,也
给大家做个参考。一起跟随小编过来看看吧
在前面的博客中,//www.jb51.net/article/106718.htm 我们使用了spring boot的异步操作,当时,我们使用的是默认的线程
池,但是,如果我们想根据项目来定制自己的线程池了,下面就来说说,如何定制线程池!
一、增加配置属性类一、增加配置属性类
package com.chhliu.springboot.async.configuration;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "spring.task.pool") // 该注解的locations已经被启用,现在只要是在环境中,都会优先加载
public class TaskThreadPoolConfig {
private int corePoolSize;
private int maxPoolSize;
private int keepAliveSeconds;
private int queueCapacity;
…………省略getter,setter方法…………
}
二、创建线程池二、创建线程池
package com.chhliu.springboot.async.pool;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.beans.factory.annotation.Autowired;
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 com.chhliu.springboot.async.configuration.TaskThreadPoolConfig;
@Configuration
@EnableAsync
public class TaskExecutePool {
@Autowired
private TaskThreadPoolConfig config;
@Bean
public Executor myTaskAsyncPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(config.getCorePoolSize());
executor.setMaxPoolSize(config.getMaxPoolSize());
executor.setQueueCapacity(config.getQueueCapacity());
executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
executor.setThreadNamePrefix("MyExecutor-");
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
三、在主类中开启配置支持三、在主类中开启配置支持
package com.chhliu.springboot.async;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.EnableAsync;
import com.chhliu.springboot.async.configuration.TaskThreadPoolConfig;
@SpringBootApplication
@EnableAsync
评论0