线程池config
@Configuration
public class ThreadPoolConfig {
@Resource
private ThreadPoolPropertiesthreadPoolProperties;
@Bean("testThreadPool")
public ThreadPoolTaskExecutortestThreadPool(){
ThreadPoolTaskExecutor threadPoolTaskExecutor =new ThreadPoolTaskExecutor();
//最大线程数
threadPoolTaskExecutor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
//核心线程数
threadPoolTaskExecutor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
//队列大小
threadPoolTaskExecutor.setQueueCapacity(threadPoolProperties.getQueueSize());
//线程最大空闲数
threadPoolTaskExecutor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());
//线程名前缀
threadPoolTaskExecutor.setThreadNamePrefix(threadPoolProperties.getThreadNamePrefix());
/**
* 自定义消费队列线程池
* CallerRunsPolicy 这个策略重试添加当前的任务,他会自动重复调用 execute() 方法,直到成功。
* AbortPolicy 对拒绝任务抛弃处理,并且抛出异常。
* DiscardPolicy 对拒绝任务直接无声抛弃,没有异常信息。
* DiscardOldestPolicy 对拒绝任务不抛弃,而是抛弃队列里面等待最久的一个线程,然后把拒绝任务加到队列。
*/
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
return threadPoolTaskExecutor;
}
}
线程池参数config
@Configuration
@Data
@ConfigurationProperties(prefix ="async")
public class ThreadPoolProperties {
@ApiModelProperty("核心线程数")
private IntegercorePoolSize;
@ApiModelProperty("最大线程数")
private IntegermaxPoolSize;
@ApiModelProperty("队列大小")
private IntegerqueueSize;
@ApiModelProperty("线程最大空闲数")
private IntegerkeepAliveSeconds;
@ApiModelProperty("线程名前缀")
private StringthreadNamePrefix;
}
线程池参数可配置到配置文件中。