定时任务和异步线程管理


前言

在肖项目模块中,我们可能会优先考虑到使用spring自带的定时任务Schedule,但是schedule默认是单线程的,在执行任务中,串行执行的效果肯定是比异步执行慢的,在定时任务的配置类中SchedulingConfigurer下面有一个configureTasks方法,我们可以在里面配置定时任务的异步线程池,但是开发中的异步不止有定时任务,一般类似导入/导出结果的也会使用的异步线程池。我们可以在一个配置类中再继承一个AsyncConfigurer接口


SchedulingConfigurer和AsyncConfigurer的联合使用

代码如下(示例):

SchedulingConfigurer的configureTasks方法

	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setTaskScheduler(taskScheduler());
    }
    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setThreadNamePrefix("Task-Thread-");
        taskScheduler.setPoolSize(taskPoolSize);
        taskScheduler.setAwaitTerminationSeconds(6000000);
        taskScheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        taskScheduler.setWaitForTasksToCompleteOnShutdown(false);
        taskScheduler.setDaemon(true);
        return taskScheduler;
    }

AsyncConfigurer的getAsyncExecutor和getAsyncUncaughtExceptionHandler

   @Override
    public Executor getAsyncExecutor() {
        return asyncTaskExecutor();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (Throwable throwable, Method method, Object... objs) -> {
//            log.error("异步任务发生错误: 方法名: {}", method.getName());
            throwable.printStackTrace();
        };
    }
    @Bean
    public AsyncTaskExecutor asyncTaskExecutor() {
        ThreadPoolTaskExecutor asyncTaskExecutor = new ThreadPoolTaskExecutor();
        asyncTaskExecutor.setThreadNamePrefix("Async-Thread-");
        asyncTaskExecutor.setCorePoolSize(3);
        asyncTaskExecutor.setQueueCapacity(100);
        asyncTaskExecutor.setMaxPoolSize(asyncPoolSize);
        asyncTaskExecutor.setKeepAliveSeconds(keepAliveSeconds);
        asyncTaskExecutor.setAllowCoreThreadTimeOut(true);
        asyncTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        asyncTaskExecutor.setWaitForTasksToCompleteOnShutdown(false);
        return asyncTaskExecutor;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值