springboot @Async自定义一个可以顺序执行线程的执行器

该博客介绍了如何在Spring中配置和使用自定义的异步任务执行器,包括一个主任务执行器和一个用于顺序执行的任务执行器。通过调整线程池参数,确保了任务的并发执行和顺序执行能力,并提供了在注解中指定执行器名称的方法。
摘要由CSDN通过智能技术生成

自定义执行器

@EnableAsync
@Configuration
public class SpringAsyncTaskConfiguration {

    @Primary
    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(8);
        executor.setMaxPoolSize(Math.max(8, Runtime.getRuntime().availableProcessors() * 2));
        executor.setQueueCapacity(2048);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("spring-async-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        return executor;
    }

    @Bean
    public TaskExecutor customTaskExecutor() {
        return buildSequentialExecutor("customTaskExecutor", 50000);
    }

    /**
     * 创建一个可以顺序执行的执行器,通过设置线程池只有一个线程和队列的方式来保证顺序执行
     * @param executorName
     * @param queueSize
     * @return
     */
    private ThreadPoolTaskExecutor buildSequentialExecutor(String executorName, int queueSize) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(1);
        executor.setMaxPoolSize(1);
        executor.setQueueCapacity(queueSize);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("spring-async-".concat(executorName));
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        return executor;
    }
}

使用

用注解@Async的时候指定执行器的名称即可,即指定beanName

@Async("customTaskExecutor")
bla...bla...
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值