@Scheduled@Async使用注意事项

使用@Scheduled的注意事项

springboot中的@Scheduled的默认执行器是ThreadPoolTaskScheduler,它是一个poolSize=1的线程池,所以项目中所有的@Scheduled定时任务会串行执行,这显然是会有问题的。此时即使在方法上加入@Async也只是把任务异步提交给到ThreadPoolTaskScheduler去执行,最终还是串行执行

解决方法:自定义TaskScheduled

@Configuration
@EnableAsync
public class ScheduleConfig {
    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(20);
        return taskScheduler;
    }
}

使用@Async时最好指定异步执行器

当使用@Async来做异步操作时,springboot默认的异步执行器是SimpleAsyncTaskExecutor,下面是它doExcute的方法

 protected void doExecute(Runnable task) {
        Thread thread = this.threadFactory != null ? this.threadFactory.newThread(task) : this.createThread(task);
        thread.start();
 }

它的核心参数如下:

  1. concurrencyLimit:并发限制数,指定了允许同时执行的最大任务数。默认值为Integer.MAX_VALUE。

  2. threadNamePrefix:线程名称前缀,用于给异步任务分配线程名称。默认值为"SimpleAsyncTaskExecutor-"。

  3. threadPriority:线程优先级,用于设置异步任务所在线程的优先级。默认值为Thread.NORM_PRIORITY。

  4. waitForTasksToCompleteOnShutdown:关闭时等待所有任务完成,指定是否在关闭时等待所有正在运行的任务完成。默认值为false。

  5. exposeUnconfigurableExecutor:暴露不可配置的执行器,指定是否将SimpleAsyncTaskExecutor实例公开为不可配置的执行器。默认值为true

如果被@Async的方法突然调用量升高,则会导致线程暴涨导致内存溢出等不可挽回的问题

解决方法:自定义线程池

@Configuration
public class TaskExecutorConfig implements AsyncConfigurer {

 private static final int CORE_POOL_SIZE = 2;

 private static final int MAX_POOL_SIZE = 2;

 private static final int QUEUE_CAPACITY = 10;
 /**
 * 通过重写getAsyncExecutor方法,制定默认的任务执行由该方法产生
 *
 * 配置类实现AsyncConfigurer接口并重写getAsyncExcutor方法,并返回一个ThreadPoolTaskExevutor
 * 这样我们就获得了一个基于线程池的TaskExecutor
 */
 @Override
 public Executor getAsyncExecutor() {
 	ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
 	taskExecutor.setCorePoolSize(CORE_POOL_SIZE);
 	taskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
 	taskExecutor.setQueueCapacity(QUEUE_CAPACITY);
 	taskExecutor.initialize();
 	return taskExecutor;
 }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

麦田小猪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值