Spring Boot 异步任务

一、简介

 

二、Spring Boot异步任务

第一步:开启异步任务,启动类添加@EnableAsync

@EnableAsync
@SpringBootApplication
public class WoniuCsdnSpringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(WoniuCsdnSpringbootApplication.class,args);
    }
}

第二步:创建异步任务线程池

@Slf4j
@Configuration
public class CsdnAsyncPool implements AsyncConfigurer {

    //自定义线程池,若不重写会使用默认的线程池
    @Bean
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(5);
        // 最大线程数
        executor.setMaxPoolSize(10);
        // 队列大小
        executor.setQueueCapacity(10);
        // 线程最大空闲时间
        executor.setKeepAliveSeconds(60);
        // 线程池中的线程的名称前缀
        executor.setThreadNamePrefix("woniu_async_");

        // 当调度器shutdown被调用时等待当前被调度的任务完成
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时长
        executor.setAwaitTerminationSeconds(60);

        /**
         线程池--拒绝策略
         ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。
         ThreadPoolExecutor.DiscardPolicy:也是丢弃任务,但是不抛出异常。
         ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程)
         ThreadPoolExecutor.CallerRunsPolicy:由调用线程处理该任务
         */
        executor.setRejectedExecutionHandler(
                new ThreadPoolExecutor.AbortPolicy()
        );

        //初始化
        executor.initialize();
        return executor;
    }

    //异步异常处理
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncExceptionHandler();
    }

    class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler{
        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
            log.info("AsyncError:{},Method:{}",throwable.getMessage(),method.getName());
            throwable.printStackTrace();
        }
    }
}

第三步:创建异步任务

@Slf4j
@Service
public class AsyncService {

    @Async("getAsyncExecutor")
    public void woniuAsync() throws InterruptedException {
        log.info("woniu async task,thread name -> {}", Thread.currentThread().getName());
    }

    @Async("getAsyncExecutor")
    public Future<String> woniuAsyncReturn() throws InterruptedException{
        log.info("woniu async return task,thread name -> {}", Thread.currentThread().getName());
        return new AsyncResult<>("woniu");
    }
}

三、IntelliJ IDEA lombok插件的安装

参考:https://blog.csdn.net/u011374856/article/details/104551009

 

实践是检验真理的唯一标准

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值