一、yml配置
# 线程池配置
spring:
task:
execution:
pool:
max-size: 10
core-size: 5
queue-capacity: 50
allow-core-thread-timeout: false
keep-alive: 500s
thread-name-prefix: thread-service-
二、配置config文件
package com.iflytek.zhsq.door.common.configure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
/**
* @Description: 初始化线程池
* @author songmo
* @Param
* @return
* @date 2020/6/28 14:52
*/
//@Configuration
@Component
@EnableAsync
public class ExecutorConfig {
private static Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);
@Value("${spring.task.execution.pool.core-size}")
private int corePoolSize;
@Value("${spring.task.execution.pool.max-size}")
private int maxPoolSize;
@Value("${spring.task.execution.pool.queue-capacity}")
private int queueCapacity;
@Value("${spring.task.execution.thread-name-prefix}")
private String namePrefix;
@Bean(name = "asyncServiceExecutor")
public Executor asyncServiceExecutor() {
logger.info("==============> start Executor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置核心线程数
executor.setCorePoolSize(corePoolSize);
//配置最大线程数
executor.setMaxPoolSize(maxPoolSize);
//配置队列大小
executor.setQueueCapacity(queueCapacity);
//配置线程池中的线程的名称前缀
executor.setThreadNamePrefix(namePrefix);
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//执行初始化
executor.initialize();
logger.info("==============> creat Executor number :" + executor.getCorePoolSize());
return executor;
}
}
三、实际应用
public void delete(String startTime) {
LOGGER.debug("delete access records :" + startTime);
startTime = String.valueOf(DateUtils.stringToDate(startTime, DateUtils.FORMATTER_L).getTime());
//获取所有需要删除的通行记录信息
RecDto recDto = new RecDto();
recDto.setEndTime(startTime);
List<RecVo> recVos = recMapper.pageList(recDto);
recMapper.delete(startTime);
//删除指定的图片信息
if (null != recVos && recVos.size() > 0) {
//定义存放图片文件集合
List<String> picList =new ArrayList<String>();
//存放图片文件集合
List<String> picUrlList =new ArrayList<String>();
recVos.forEach(recVo ->{
if (null != recVo.getPic()) {
picList.add(recVo.getPic());
picUrlList.add(recVo.getPicUrl());
}
if(null !=recVo.getBackPic()){
picList.add(recVo.getBackPic());
picUrlList.add(recVo.getBackPicUrl());
}
});
//批量删除图片信息
pictureMapper.deletePicCode(picList);
//线程池删除文件
picUrlList.forEach(string -> {
//删除pic
executor.execute(() -> {
delectPicFile(string);
});
});
}
}