关于若依里面线程池的配置解读

发布时间 2024-01-03 16:24:30作者: xiaobaibao

1.线程池配置:只有配置了才可以进行使用

/**
* 线程池配置
*
* @author ruoyi
**/
@Configuration
public class ThreadPoolConfig
{
// 核心线程池大小
private int corePoolSize = 50;

// 最大可创建的线程数
private int maxPoolSize = 200;

// 队列最大长度
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;
}

/**
* 执行周期性或定时任务
*/
@Bean(name = "scheduledExecutorService")
protected ScheduledExecutorService scheduledExecutorService()
{
return new ScheduledThreadPoolExecutor(corePoolSize, // 核心线程数
// 同时,使用BasicThreadFactory.Builder()构建一个基本线程工厂,使用指定的命名模式"schedule-pool-%d"命名线程,并设置线程为守护线程(daemon=true)。
new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(),
// 最后,使用ThreadPoolExecutor.CallerRunsPolicy()作为饱和策略,当任务无法提交到线程池时,由提交任务的线程直接执行。
new ThreadPoolExecutor.CallerRunsPolicy())
{
// 在每个任务执行完毕后,会调用afterExecute()方法,这里的重写逻辑是打印任务执行过程中的异常信息。
@Override
protected void afterExecute(Runnable r, Throwable t)
{
super.afterExecute(r, t);
Threads.printException(r, t);
}
};
}
}

2.进行使用示例:

@Component
public class OrderStatusUpdater {

@Autowired
private OrderRepository orderRepository; // 假设你有一个名为OrderRepository的订单仓库

@Autowired
private ScheduledExecutorService scheduledExecutorService;

@Scheduled(cron = "0 0 11 * * ?") // 在每天的11点执行任务
public void updateOrderStatus() {
scheduledExecutorService.submit(() -> {
// 执行更新操作
orderRepository.updateStatusToZero();
});
}
}

3.如果不使用 submit 方法的话还有好多种别的方式,但是要根据具体需求进行变化,以下是相应介绍:

除了submit方法,scheduledExecutorService接口还提供了其他可以执行任务的方法,例如:

execute(Runnable command): 提交一个不返回结果的任务进行执行,并返回一个Future对象。这个方法的主要区别是它不返回任何结果,无法获取任务执行的结果。

schedule(Callable<V> callable, long delay, TimeUnit unit): 在给定的延迟时间后执行给定的任务,并返回一个Future对象来获取任务的结果。该方法的参数callable是一个带有返回值的任务,delay是执行任务的延迟时间,unit是时间单位。

schedule(Runnable command, long delay, TimeUnit unit): 在给定的延迟时间后执行给定的任务,无返回结果。

scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit): 创建并执行一个周期性任务,每隔一段时间执行一次,无返回结果。其中initialDelay是初始延迟时间,period是周期时间,unit是时间单位。

scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit): 创建并执行一个周期性任务,每次任务执行完成后间隔一段时间再执行,无返回结果。其中initialDelay是初始延迟时间,delay是间隔时间,unit是时间单位。