线程池配置
package com.ruoyi.framework.config;
import com.ruoyi.common.utils.Threads;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 线程池配置
*
* @author ruoyi
**/
@Configuration
public class ThreadPoolConfig
{
// 核心线程池大小
private int corePoolSize = 2;
// 最大可创建的线程数
private int maxPoolSize = 2;
// 队列最大长度
private int queueCapacity = 1000;
// 线程池维护线程所允许的空闲时间
private int keepAliveSeconds = 300;
@Bean(name = "threadPoolTaskExecutor")
public ThreadPoolTaskExecutor threadPoolTaskExecutor()
{
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setMaxPoolSize(maxPoolSize);
executor.setCorePoolSize(corePoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveSeconds);
// 线程池对拒绝任务(无线程可用)的处理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
异步类
@Component
public class AsyncTxtUtil
{
private static final Logger log = LoggerFactory.getLogger(AsyncTxtUtil.class);
@Async("threadPoolTaskExecutor")
public void sendMessage1() {
log.info("发送短信方法---- 1 执行开始");
try {
Thread.sleep(20000); // 模拟耗时
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
log.info("发送短信方法---- 1 执行结束");
}
}
调用类
@Service
public class TDayServiceImpl{
@Autowired
private AsyncTxtUtil asyncTxtUtil;
public String importDay() {
String path = "E:/project/ruo-yi-vue/stock/";
File[] childrenFiles = new File(path).listFiles();
for (File childFile : childrenFiles) {
asyncTxtUtil.sendMessage1(); // 发短信的方法 1
}
}
}
启动类加@EnableAsync
@SpringBootApplication(exclude ={DataSourceAutoConfiguration.class})
//开启多线程
@EnableAsync
public class RuoYiApplication {
public static void main(String[] args) {
SpringApplication.run(RuoYiApplication.class, args);
}
}
@Async调用失败,调异步方法和异步方法在同一个类
https://blog.csdn.net/weixin_44371237/article/details/132673310